一行代码能搞定的事,为什么要写两行?

80 阅读2分钟

1,用三元运算符代替简单的if else

if(deposit >= 1000000){
    me = '辞职回家过退休生活!'
} else {
    me = '继续打工艰苦奋斗!'
}

改成三元表达式

me = deposit >= 1000000 ? '辞职回家过退休生活!' : '继续打工艰苦奋斗!'

2,当需要判断的情况不止一个时,第一个想法就是使用 || 或运算符

/** 这种方式就非常麻烦还容易出错 */
if( 
    type == 1 ||  
    type == 2 ||  
    type == 3 ||  
    type == 4 ||  
){
   //...  
}

ES6中的includes一行就能搞定

if( [1,2,3,4,5].includes(type) ) {
    //...
}

3,日常写代码常用到的取值操作

const obj = {
    a:1,
    b:2,
    c:3,
}
//以前的取值方式
const a = obj.a;
const b = obj.b;
const c = obj.c;

使用ES6的 解构赋值 一行就能搞定

const{a,b,b}= obj

4,常常会遇到获取一个值并赋给另一个变量的情况,在获取这个值时需要先判断一下这个对象是否存在,才能进行赋值

if(obj && obj.name){   
    const name = obj.name
}

ES6提供了可选连操作符?.,可以简化操作,非常方便,快用起来

const name = obj?.name;

5,ES6移除数组中的重复项

const data = (arr) => [...new Set(arr)];
console.log(data([1, 2, 2, 2, 3, 4, 4, 5, 6, 6]));
// [1, 2, 3, 4, 5, 6]

6,去除重复的对象,对象的key值和value值都分别相等,才叫相同对象

const dataObj = (arr, fn) =>arr.reduce((acc, v) => {
    if (!acc.some(x => fn(v, x))) acc.push(v);return acc;
}, []);   
dataObj([{id1, name'孙悟空'}, {id2, name'猪八戒'}, {id1, name'孙悟空'}], (a, b) => a.id == b.id) 
// [{id: 1, name: '孙悟空'}, {id: 2, name: '猪八戒'}]

7,使用ES6的语法来合并三个数组并去重

const arr1 = [1, 2, 3];
const arr2 = [2, 3, 4];
const arr3 = [3, 4, 5];
const mergedArr = Array.from(new Set([...arr1, ...arr2, ...arr3]));
console.log(mergedArr); // [1, 2, 3, 4, 5]

8,合并三个JSON数组并根据id属性进行去重

const arr1 = [{id: 111, name: '郭靖'},{id: 222, name: '黄蓉'},{id: 222, name: '郭芙'}];
const arr2 = [{id: 444, name: '杨过'},{id: 555, name: '小龙女'},{id: 111, name: '杨康'}];
const arr3 = [{id: 666, name: '张无忌'},{id: 777, name: '赵敏'},{id: 222, name: '周芷若'}];
const mergedArr = [...arr1, ...arr2, ...arr3].reduce((result, current) => {
    const existingItem = result.find(item => item.id === current.id);
    if (!existingItem) {
        result.push(current);
    }
    return result;
}, []);
console.log(mergedArr);
// [{"id"111,"name""郭靖"}, {"id"222,"name""黄蓉"},{"id"444,"name""杨过"},
{"id"555,"name""小龙女"},{"id"666,"name""张无忌"},{"id"777,"name""赵敏"}]

下期总结ES中数组的几种用法