ES6+ 新特性
我们把 ES6(也叫 ES2015) 以后更新的所有 JavaScript 标准规范新增的 API 叫做 ES6+ 新特性。
最新的 ES6 到 ES12 语法引入的很多新特性,能让很多依赖第三方库才能做到的事用原生 JS 寥寥几行代码就可迎刃而解。
本文只列举常用的特性和最基础的使用场景,详细介绍的话内容量将十分巨大,不妨通过 Google 搜索国外开发者的文档以及参阅 ECMA 官方发布的标准。
备注:ES6+ 新特性系列一共包含了 6 篇文章,更多内容请移步至🚶🚶🚶->你想知道的前端都在这里,本文接上篇文章->ES6 新特性之ES7-ES10(五)
ES11
ES11 - String.prototype.matchAll()
matchAll() 方法返回一个包含所有匹配正则表达式及分组捕获结果的迭代器。
let str = '11223344113311'
console.log(str.match('11')) // ['11', index: 0, input: '11223344113311', groups: undefined], 返回一个数组
console.log(str.matchAll('11')) // RegExpStringIterator {}, 返回一个迭代器
可以看到,matchAll 是通过 Generator 来实现的。
ES11 - BigInt
在 ES11 增加了新的原始数据类型:BigInt,表示一个任意精度的整数,可以表示超长数据,可以超出 2 的 53 次方。
JS 中 Number 类型只能安全的表示 -(2⁵³-1) 至 2⁵³-1 范围的值
使用 BigInt 有两种方式:
// 1.数字后面增加 n
const bigInt = 9007199254740993n
console.log(bigInt)
console.log(typeof bigInt) // bigint
console.log(1n == 1) // true
console.log(1n === 1) // false
// 2.使用 BigInt 函数
const bigIntNum = BigInt(9007199254740993n)
console.log(bigIntNum) // 9007199254740993n
ES11 - Promise.allSettled()
ES6 新特性 Promise.all() 具有并发执行异步任务的能力。但它的最大问题就是如果其中某个任务出现异常(reject),所有任务都会挂掉,Promise 直接进入 reject 状态。而 Promise.allSettled 在并发任务中,无论一个任务正常或者异常,都会返回对应的的状态。
Promise.allSettled([
Promise.reject({
code: 500,
msg: '服务异常'
}),
Promise.resolve({
code: 200,
data: ['1', '2', '3']
}),
Promise.resolve({
code: 200,
data: ['4', '5', '6']
})
]).then(res => {
console.log(res)
// console.log('成功')
const data = res.filter(item => item.status === 'fulfilled')
console.log(data)
}).catch(err => {
console.log(err)
console.log('失败')
})
ES11 - 空值合并运算符(??)
空值合并运算符(??)是一个逻辑运算符。当左侧操作数为 null 或 undefined 时,其返回右侧的操作数。否则返回左侧的操作数。
const b = 0 // 或者 null undefined false
const a = b ?? 123
console.log(a) // 0
空值合并运算符(??)我们仅在第一项为 null 或 undefined 时设置默认值。
ES12
ES12 - String.prototype.replaceAll()
replaceAll() 方法返回一个全新的字符串,所有符合匹配规则的字符都将被替换掉。
const str = 'PHP is the best language, I love the PHP, are you interested in PHP?';
const newStr = str.replaceAll('PHP', 'JavaScript');
console.log(newStr);
// "JavaScript is the best language, I love the JavaScript, are you interested in JavaScript?"
ES12 - Promise.any() 和 AggregateError
Promise.any() 接收一个 Promise 可迭代对象,只要其中的一个 promise 提前成功,就直接返回那个已经成功的 promise。
如果可迭代对象中没有一个 promise 成功(即所有的 promise 都失败/拒绝),就返回一个失败的 promise 和 AggregateError 类型的实例(它是 Error 的一个子类,用于把单一的错误集合在一起)。
本质上,这个方法和 Promise.all() 是相反的。
const p1 = new Promise((resolve, reject) => {
setTimeout(
() => resolve("promise one"),
Math.floor(Math.random() * 100)
);
});
const p2 = new Promise((resolve, reject) => {
setTimeout(
() => resolve("promise two"),
Math.floor(Math.random() * 100)
);
});
const p3 = new Promise((resolve, reject) => {
setTimeout(
() => resolve("promise three"),
Math.floor(Math.random() * 100)
);
});
(async function() {
const result = await Promise.any([p1, p2, p3]);
console.log(result);
})();
上述代码可以随机输出 promise one,promise two,promise three。 如果将上述代码改成所有的都 reject,那么会抛出 AggregateError:
const p1 = new Promise((resolve, reject) => {
setTimeout(
() => reject("promise one rejected"),
Math.floor(Math.random() * 100)
);
});
const p2 = new Promise((resolve, reject) => {
setTimeout(
() => reject("promise two rejected"),
Math.floor(Math.random() * 100)
);
});
const p3 = new Promise((resolve, reject) => {
setTimeout(
() => reject("promise three rejected"),
Math.floor(Math.random() * 100)
);
});
try{
(async function() {
const result = await Promise.any([p1, p2, p3]);
console.log(result);
})();
} catch(error) {
console.log(error.errors);
}
报的错如下:
Uncaught (in promise) AggregateError: All promises were rejected
注意:必须是所有的 promise 都被 reject 之后才会抛出 AggregateError,如果有部分成功,那么将会返回成功的结果。
ES12 - 数字分隔符
这个新特性是为了方便程序员看代码而出现的,如果数字比较大,那么看起来就不是那么一目了然,比如下面的长数字:
const number = 1_000_000_000_000; // 十进制
const binary = 0b1010_0101_1111_1101; // 二进制
const hex = 0xAF_BF_C3; // 十六进制
💐💐💐至此,认真地恭喜你!!!💐💐💐看到这里你已经掌握重点的 ES6+ 新特性了,很开心你学到了这些知识点,顺手给个赞和关注吧,你的鼓励是我不断分享的动力!😊😊😊