ES6常用方法

1,729 阅读1分钟

ES6虽然发布很久了,但是工作中却发现用的人也还不多,尤其是工作经验少的前端开发,或者是一些需要前后端都开发的后端开发,甚至看到一些ES6的写法却不知道是什么意思,下面我介绍一些常用的ES6写法:

1.常用的取值方法

这样的取值方法方便从一个对象中取多个值

1.
const obj = {
    name: '小王',
    age:20,
}

const {name, age} = obj || [];
const param = {
    array: [1,2,3,4],
    obj:{a:1,a1:2}
}
const {array, obj} = obj || [];
或
const {a:name} = obj;
console.log(a1);// 小王
2.
const param = {
    array: [1,2,3,4],
    obj:{a:1,a1:2}
}
const {array, obj} = obj || [];
或
const {a:array} = obj;
console.log(array);// [1,2,3,4]
2.合并数据

我们经常会对数组或者对象进行合并显示或者传入接口(浅拷贝)

const arr1 = ['a1','a2','a3']; const arr2 = ['b1','a1','b2']; const c = [...new Set([...arr1,...arr2])];//['a1','a2','a3','b1','b2']
const obj1 = { a:1, } const obj2 = { b:1, } const obj = {...obj1,...obj2};//{a:1,b:1}
3.对字符串进行拼接
const date = '2021-10-01';
const score = 90;
const result = `${date}${score > 90?'优秀':'加油!'}`;
4.对数组进行查询

通常我们在数据进行匹配的时候会对数组中的对象进行匹配通过关键字拿到某条数据

const data = [{id: 1, name: '小王', age: 20}, {id: 2, name: '小王', age: 18}, {id: 3, name: '小王', age: 18}];
const result = data.find( 
  item =>{
    return item.id === 1
  }
)
console.log(result) // {id: 1, name: '小王', age: 20}
5.IF判断

针对多个条件判断

const condition = [1,2,3,4];
if( condition.includes(type) ){
   //...
}
6.涉及到为空或者undefined的判断
if(value??'' !== ''){

  //...

}