2022年,ES6 的 8 个实践总结

86 阅读1分钟

hello,小伙伴们,还有两个月,2022年就结束了。 前端小杨总结了工作中非常实用的 8 个 ES6 特性。 快来看看你都用上了吗?!

一、声明变量

let a = 1//a可以重新赋值
const a = 1//a不可以重新赋值

二、变量的解构赋值

数组

const [a, b, c, d = 4] = [1, 2, 3];

对象

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

还可以设置默认值。

三、模板字符串

const a = 'hello';
const b = 1, c = 2;
const d = `${a}${b + c}`;//变量、表达式

四、优雅运算符

?.

const b = a && a.b;

const b = a?.b;

??

const c = b != undefined ? b : 1;

const c = b ?? 1;

...

const a = [1, 2];
const b = [...a];  // [1, 2], b !== a

五、数组

扩展运算符

可替换 concat

const a = [1, 2];
const b = [3, 4];
const c = a.concat(b);

const c = [...a, ...b]; //TS中ab不同类型时,用这个更方便

includes()

if(a === 1 || a===2 || a===3) {}

变:

if([1, 2, 3].includes(a)) {}

from()

去重数组

const a = [1, 2, 3, 1];
const b = Array.from(new Set(a)); //[1, 2, 3]

查找

find()、findIndex()、findLast()、findLastIndex()

const a = [1, 2, 3, 1];
const b = a.find(v => v < 2); //1
const c = a.findIndex(v => v < 2);//0
const d = a.findLast(v => v < 2);//1
const e = a.findLastIndex(v => v < 2);//3

遍历

keys()、values()、entries()

const a = [1, 2, 3];
for (let i of a.keys()) {
  console.log(i);
}
//0 1 2
for (let v of a.values()) {
  console.log(v);
}
//1 2 3
for (let [i, v] of a.entries()) {
  console.log(i, v);
}
// 0 1
// 1 2
// 2 3

at()

取数组最后一个值(真优雅)

const a = [1, 2, 3];
const b = a[a.length - 1]; // 3

cosnt b = a.at(-1); // 3

六、对象

Object.assign()

const o = {
    a: 1,
    b: 2
};
const c = Object.assign({}, o, {c: 3}); 

扩展运算符

可替换 Object.assign();

const o = {
    a: 1,
    b: 2
};
const c = {...a, c:3}; 

遍历

keys()、values()、entries()

let { keys, values, entries } = Object;
let o = { a: 1, b: 2, c: 3 };

for (let key of keys(o)) {
  console.log(key); // 'a', 'b', 'c'
}

for (let value of values(o)) {
  console.log(value); // 1, 2, 3
}

for (let [key, value] of entries(o)) {
  console.log([key, value]); // ['a', 1], ['b', 2], ['c', 3]
}

七、异步

callback->promise->async/await

解决回调炼狱,越来越优雅

const a = async () => {};
const b = async () => {};
const c = async () => {
    const v1 = await a();
    const v2 = await b();
};

八、箭头函数

const a = function () {}

const a = () => {}

以上便是开发过程中常用的一些 ES6 特性,2022.11.02 记。

还有一些特性暂时没有使用场景, 以后使用了会继续更新。

感谢大家阅读, 欢迎指正、建议!!