1 2 3 4

关于使用es新特性优化代码这回事

1.解构

const obj = {
    a:1,
    b:2,
    c:3,
    d:4,
    e:5,
}

const a = obj.a;
const b = obj.b;
const c = obj.c;
const d = obj.d;
const e = obj.e;

const f = obj.a + obj.d;
const g = obj.c + obj.e;

改进写法

const {a,b,c,d,e} = obj;
const f = a + d;
const g = c + e;

2.合并数据

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 obj2 = {
  b:1,
}
const obj = Object.assign({}, obj1, obj2);//{a:1,b:1}

改进写法

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.if判断条件改进

if(
    type == 1 ||
    type == 2 ||
    type == 3 ||
    type == 4 ||
){
   //...
}

改进后

const condition = [1,2,3,4];

if( condition.includes(type) ){
   //...
}

4.列表搜索

const a = [1,2,3,4,5];
const result = a.filter( 
  item =>{
    return item === 3
  }
)

改进

const a = [1,2,3,4,5];
const result = a.find( 
  item =>{
    return item === 3
  }
)

5.扁平化数组

// 一个部门JSON数据中,属性名是部门id,属性值是个部门成员id数组集合,现在要把有部门的成员id都提取到一个数组集合中。
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)]

改进

const deps = {
    '采购部':[1,2,3],
    '人事部':[5,8,12],
    '行政部':[5,14,79],
    '运输部':[3,64,105],
}
let member = Object.values(deps).flat(Infinity);

6.获取对象属性值

const name = obj && obj.name;

改进后

const name = obj?.name;

7.添加对象属性(动态属性名)

let obj = {};
let index = 1;
let key = `topic${index}`;
obj[key] = '话题内容';

改进后

let obj = {};
let index = 1;
obj[`topic${index}`] = '话题内容';

8.输入框非空判断

if(value !== null && value !== undefined && value !== ''){
    //...
}

改进后

if((value??'') !== ''){
  //...
}

 

posted @ 2023-02-24 08:32  无序  阅读(16)  评论(0编辑  收藏  举报