1.解构赋值
const obj = { a:1, b:2, c:3, d:4, e:5, }
const {a,b,c,d,e} = obj;
如果想创建的变量名和对象的属性名不一致,const {a:a1} = obj;
注意解构的对象不能为undefined
、null
。否则会报错,故要给被解构的对象一个默认值,
const {a,b,c,d,e} = obj || {};
2.扩展运算符
如合并两个数组,合并两个对象
const a = [1,2,3]; const b = [1,5,6];
合并:const c = [...new Set([...a,...b])];//[1,2,3,5,6]
const obj1 = { a:1, } const obj2 = { b:1, }
合并:const obj = {...obj1,...obj2};//{a:1,b:1}
3.模板字符串
const name = '小明'; const score = 59;
const result = `${name}${score > 60?'的考试成绩及格':'的考试成绩不及格'}`
注:在${}
中可以放入任意的JavaScript表达式,可以进行运算,以及引用对象属性。
4.数组实例方法-incloudes
const condition = [1,2,3,4];
if( condition.includes(type) ){
//...
}
5.精确搜索用find
find
方法中,找到符合条件的项,就不会继续遍历数组。
const a = [1,2,3,4,5];
const result = a.find(
item =>{
return item === 3
}
)
6.获取对象的全部属性值-Object.values,数组的扁平化处理-flat
const deps = {
'采购部':[1,2,3],
'人事部':[5,8,12],
'行政部':[5,14,79],
'运输部':[3,64,105],
}
let member = Object.values(deps).flat(Infinity);
其中使用Infinity
作为flat
的参数,使得无需知道被扁平化的数组的维度。但是flat
方法不支持IE浏览器。
7.可选链操作符
获取对象属性值const name = obj?.name;
8.ES6中的对象属性名是可以用表达式
let obj = {};
let index = 1;
obj[`topic${index}`] = '话题内容';
9.空值合并运算
if((value??'') !== ''){
//...
}
10.async,await
const fn = async () =>{
const res1 = await fn1();
const res2 = await fn2();
console.log(res1);// 1
console.log(res2);// 2
}
补充
但是要做并发请求时,还是要用到Promise.all()
const fn = () =>{
Promise.all([fn1(),fn2()]).then(res =>{
console.log(res);// [1,2]
})
}