本文集合了 ES6 至 ES11 常用到的特性,包括还在规划的 ES12。

ES6(2015)

类(class)

1
2
3
4
5
6
7
8
9
10
class People {
constructor(name) {
this.name = "a";
}
console() {
console.log(this.name);
}
}
const people = new People("a");
people.console(); // a

模块化(ES Module)

1
2
3
4
5
6
// A.js 导出一个方法
export const addNum = (a, b) => a + b;

// B.js 导入并使用
import { addNum } from "./A.js";
addNum(1, 2); // 3

箭头函数

1
2
const addNum = (a, b) => a + b;
addNum(1, 2); // 3

函数参数默认值

1
function func(val = 10,list= []){...}

字符串模板

1
2
const name = "张三";
const text = `this is ${name}`;

解构赋值

1
2
3
4
5
6
const obj = { name: "张三", age: 22 };
const { name, age } = obj; // "张三" 22

var a = 1,
b = 2;
[a, b] = [b, a]; // a 2 b 1

展开运算符

1
const data = [..."hello"]; // ['h','e','l','l','o']

对象属性简写

1
2
3
const name = "张三",
age = 22;
const obj = { name, age }; // 张三 22 等同于const obj = {name:name,age:age}

Promise

1
2
3
4
5
Promise.resolve().then(() => {
console.log(2);
});
console.log(1);
// 先打印 1 ,再打印 2

let/const

1
2
let a = 1;
const b = {};

ES7(2016)

Array.prototype.includes()

1
[1, 2, 3].includes(2); // true

指数操作符

1
2 ** 10; // 1024

ES8 (2017)

async/await

异步解决方案

1
2
3
async function Async() {
const res = await setTimeout(() => {});
}

Object.values()

1
Object.values({ a: 1, b: 2, c: 3 }); // [1,2,3]

Object.entries()

1
Object.entries({ a: 1, b: 2, c: 3 }); // [["a", 1], ["b", 2], ["c", 3]]

String padding

1
2
3
4
// padStart
"hello".padStart(10); // " hello"
// padEnd
"hello".padEnd(10); //"hello "

Object.getOwnPropertyDescriptors()

获取一个对象的所有自身属性的描述符,如果没有任何自身属性,则返回空对象。

1
2
3
4
5
6
7
8
9
const obj = { name: "张三", age: 22, todo: function () {} };
const obj1 = {};
Object.getOwnPropertyDescriptors(obj);
//age: {value: 22, writable: true, enumerable: true, configurable: true}
//name: {value: "张三", writable: true, enumerable: true, configurable: true}
//todo: {writable: true, enumerable: true, configurable: true, value: ƒ}
//__proto__: Object

Object.getOwnPropertyDescriptors(obj1); // {}

SharedArrayBuffer 对象

SharedArrayBuffer 对象用来表示一个通用的,固定长度的原始二进制数据缓冲区

1
2
3
4
5
6
/**
*
* @param {*} length 所创建的数组缓冲区的大小,以字节(byte)为单位。
* @returns {SharedArrayBuffer} 一个大小指定的新 SharedArrayBuffer 对象。其内容被初始化为 0。
*/
new SharedArrayBuffer(10);

ES9(2018)

异步迭代

await 可以和 for…of 循环一起使用,以串行的方式运行异步操作

1
2
3
4
5
async function proess(array) {
for await (let i of array) {
//...
}
}

Promise.finally()

1
2
3
4
Promise.resolve()
.then()
.catch((e) => e)
.finally();

正则表达式命名捕获组

1
2
const reg = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/;
const match = reg.exec("2021-05-31");

正则表达式 dotAll 模式

正则表达式中点.匹配除回车外的任何单字符,标记 s 改变这种行为,允许行终止符的出现

1
/hello.world/.test("hello\nworld"); // false

ES10(2019)

Array.flat()/Array.flatMap()

  • flat()
1
[1, 2, [3, 4]].flat(Infinity); // [1, 2, 3, 4]
  • flatMap()
1
[1, 2, 3, 4].flatMap((a) => [a ** 2]); // [1, 4, 9, 16]

String.trimStart()/String.trimEnd()

去除字符串首尾空白字符

1
2
3
4
5
// trimStart()
" hello".trimStart(); // "hello"

//trimEnd()
"hello ".trimEnd(); // "hello"

String.prototype.matchAll

matchAll()为所有匹配的匹配对象返回一个迭代器

1
2
const raw_arr = "test1  test2  test3".matchAll(/t(e)(st(\d?))/g);
const arr = [...raw_arr];

Symbol.prototype.description

只读属性,返回 Symbol 对象的可选描述的字符串。

1
Symbol("hello").description; // "hello"

Object.fromEntries()

返回一个给定对象自身可枚举属性的键值对数组

1
2
3
4
5
6
// 通过 Object.fromEntries, 可以将 Map 转化为 Object:
const map = new Map([
["foo", "bar"],
["baz", 42],
]);
console.log(Object.fromEntries(map)); // { foo: "bar", baz: 42 }

ES11(2020)

Nullish coalescing Operator(空值处理)

表达式在 ?? 的左侧运算符求值为 undefined 或 null,返回其右侧。

1
2
3
4
5
6
7
8
9
10
11
let user = {
u1: 0,
u2: false,
u3: null,
u4: undefined,
u5: "",
};
let u2 = user.u2 ?? "用户2"; // false
let u3 = user.u3 ?? "用户3"; // 用户3
let u4 = user.u4 ?? "用户4"; // 用户4
let u5 = user.u5 ?? "用户5"; // ''

Optional chaining(可选链)

?.用户检测不确定的中间节点

1
2
3
let user = {};
let u1 = user.childer.name; // TypeError: Cannot read property 'name' of undefined
let u1 = user.childer?.name; // undefined

Promise.allSettled

返回一个在所有给定的 promise 已被决议或被拒绝后决议的 promise,并带有一个对象数组,每个对象表示对应的 promise 结果

1
2
3
4
5
6
7
8
9
10
11
12
const promise1 = Promise.resolve(3);
const promise2 = 4;
const promise3 = new Promise((resolve, reject) =>
reject("我是失败的Promise_1")
);
const promise4 = new Promise((resolve, reject) =>
reject("我是失败的Promise_2")
);
const promiseList = [promise1, promise2, promise3, promise4];
Promise.allSettled(promiseList).then((values) => {
console.log(values);
});

import()

按需导入

新基本数据类型 BigInt

任意精度的整数

1
BigInt(12); // 12n

globalThis

  • 浏览器:window
  • worker:self
  • node:global

ES12(2021)

replaceAll

返回一个全新的字符串,所有符合匹配规则的字符都将被替换掉

1
2
const str = "hello world";
str.replaceAll("l", ""); // "heo word"

Promise.any

Promise.any() 接收一个 Promise 可迭代对象,只要其中的一个 promise 成功,就返回那个已经成功的 promise 。如果可迭代对象中没有一个 promise 成功(即所有的 promises 都失败/拒绝),就返回一个失败的 promise

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const promise1 = new Promise((resolve, reject) =>
reject("我是失败的Promise_1")
);
const promise2 = new Promise((resolve, reject) =>
reject("我是失败的Promise_2")
);
const promiseList = [promise1, promise2];
Promise.any(promiseList)
.then((values) => {
console.log(values);
})
.catch((e) => {
console.log(e);
});

// Promise {<fulfilled>: undefined}
// __proto__: Promise
// [[PromiseState]]: "fulfilled"
// [[PromiseResult]]: undefined

逻辑运算符和赋值表达式

逻辑运算符和赋值表达式,新特性结合了逻辑运算符(&&,||,??)和赋值表达式而 JavaScript 已存在的 复合赋值运算符有:

1
2
3
4
5
6
7
8
9
10
11
a ||= b;
//等价于
a = a || (a = b);

a &&= b;
//等价于
a = a && (a = b);

a ??= b;
//等价于
a = a ?? (a = b);

数字分隔符

数字分隔符,可以在数字之间创建可视化分隔符,通过_下划线来分割数字,使数字更具可读性

1
2
3
4
5
const money = 1_000_000_000;
//等价于
const money = 1000000000;

1_000_000_000 === 1000000000; // true