看到一篇文章,很是受用,稍作总结。
一、取值
ES5例子:
const obj = { 'name':'小明', 'age':25,'subject':'英语'}
const name = obj.name;
const age = obj.age;
const subject = obj.subject;
解决方案 :ES6的解构,写法如下
const {name, age, subject} = obj;
也可以重新命名
const {name:new_name, age:new_age, subject} = obj;
要注意解构的对象不能为undefined、null。所以一般要给解构的对象一个默认值。
const {name, age, subject} = obj || {};
二、合并对象
ES5例子
// 数组合并
const a = [1,2,3];
const b = [1,5,6];
const c = a.concat(b); // [1,2,3,1,5,6]
// 对象合并
const obj1 = { a: 1 }
const obj1 = { b: 1 }
const obj = Object.assgin({}, obj1, obj2); // {a:1,b:1}
ES6的改进,利用new Set实现数组的去重合并
// new Set()合并去重
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}
三、字符串拼接
const name = '小明';
const score = 59;
let result = '';
if(score > 60){
result = `${name}的考试成绩及格`;
}else{
result = `${name}的考试成绩不及格`;
}
这种写法看着就很冗余啰嗦,正确高效的使用字符串模板
const name = '小明';
const score = 59;
const result = `${name}的考试成绩${score > 60?'及格':'不及格'}`;
四、关于if
if(
type == 1 ||
type == 2 ||
type == 3 ||
type == 4 ||
){
//...
}
这可真是硬伤,用ES6的includes吧
const arr = [1,2,3,4];
if( arr.includes(type) ){
//...
}
五、扁平化处理
ES5写法:
const deps = {
'采购部':[1,2,3],
'人事部':[5,8,12],
'行政部':[5,14,79],
'运输部':[3,64,105],
}
let member = [];
for (let item in deps){
const value = deps[item];
if(Array.isArray(value)){
member = [...member,...value]
}
}
member = [...new Set(member)]
看着就不想去解读的代码,何不用ES6的Object.values和flat呢?一下子十几行的代码就用几行就解决了,看着清清爽爽,也更便于别人去看你的代码
const deps = {
'采购部':[1,2,3],
'人事部':[5,8,12],
'行政部':[5,14,79],
'运输部':[3,64,105],
}
let member = Object.values(deps).flat(Infinity);
六、获取对象属性值
let obj = {};
let index = 1;
let key = `topic${index}`;
obj[key] = '话题内容';
改进
let obj = {};
let index = 1;
obj[`topic${index}`] = '话题内容';
七、关于非空的判断
我们在处理业务代码时经常会需要作判空处理
if(value !== null && value !== undefined && value !== ''){
//...
}
ES6中新出的空值合并运算符是不是会更简洁
if(value??'' !== ''){
//...
}
八、关于异步函数
const fn1 = () =>{
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1);
}, 300);
});
}
const fn2 = () =>{
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2);
}, 600);
});
}
const fn = () =>{
fn1().then(res1 =>{
console.log(res1);// 1
fn2().then(res2 =>{
console.log(res2)
})
})
}
照这么写下去可真是人间地狱,回调再回调,还好有ES6
const fn = async () =>{
const res1 = await fn1();
const res2 = await fn2();
console.log(res1);// 1
console.log(res2);// 2
}