ES6用法

59 阅读1分钟

解构赋值

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

// ES6解构的对象不能为`undefined`、`null`。否则会报错,要给被解构的对象一个默认值 {}

const {a, b. c, d} = obj || {};
console.log(a) // 1

// 数据对象中的属性名不是想要的,可以创建变量名和属性名
const {a: a1} = obj || {};
console.log(a1) // 1

合并两个对象

const obj1 = {
    a: 1
}
const obj2 = {
    b: 1
}

const obj3 = {...obj1,...obj2} // {a:1, b:1}

合并两个数组并去重

const a = [1,2,3];

const b = [1,3,4];

const c = [...new Set([...a,...b])] // [1,2,3,4]

if 条件判断

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

const condition = [1,2,3,4];
if (condition.includes(type)) { ... }

从数组中找出符合的项

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

非空判断

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

异步函数

const fn = async() => {
    const res1 = await fn1();
    const res2 = await fn2();
    console.log(res1); // 1
    console.log(res2); // 2
}

// 并发请求
const fn = () => {
    Promise.all([fn1(), fn2()]).then(res => {
        console.log(res); // 1,2
    })
}