ES6增加代码“高级感”

192 阅读3分钟

1.在obj中取值的方法

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

es5通常是用‘.’来获取,感觉不够优雅

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;

而es6仅需要使用解构就可以获得值

5行代码用1行代码

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

补充

结构赋值虽然好用但是需要及时判空(注意解构的对象不能为undefinednull。否则会报错,故要给被解构的对象一个默认值。)

const {a,b,c,d,e} = obj || {};

2. 数组对象的数据合并

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中可以使用扩展运算符来简化操作

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.字符串拼接

${}中可以放入任意的JavaScript表达式,可以进行运算,以及引用对象属性。

// 臃肿示范
const name = '小明';
const score = 59;
let result = '';
if(score > 60){
  result = `${name}的考试成绩及格`
}else{
  result = `${name}的考试成绩不及格`
}

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

// 改进
const name = '小明';
const score = 59;
const result = `${name}${score > 60?'的考试成绩及格':'的考试成绩不及格'}`;


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


if判断条件

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

在判断某个值状态可以考虑下include的使用

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

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

5.关于列表搜索

在项目中,一些没分页的列表的搜索功能由前端来实现,搜索一般分为精确搜索和模糊搜索。搜索也要叫过滤,一般用filter来实现。

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

如果是精确搜索用findfind方法中找到符合条件的项,就不会继续遍历数组。

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

6.扁平化数组

一个部门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)]

获取属性值可以用es6中的Object.value,扁平化数组可以用到flat这个方法。

const deps = {
    '采购部':[1,2,3],
    '人事部':[5,8,12],
    '行政部':[5,14,79],
    '运输部':[3,64,105],
}
//其中使用`Infinity`作为`flat`的参数,使得无需知道被扁平化的数组的维度。
let member = Object.values(deps).flat(Infinity);

7. 获取对象的属性

当获取动态对象的属性时可能对象为空,要进行判空操作

const name = obj && obj.name;

ES6中的可选链操作符可以简洁的解决判空问题

const name = obj?.name;

8. 输入框非空的判断

处理输入框相关业务时,往往会判断输入框未输入值的场景

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

// 这时候使用合并运算符处理更简洁

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