ES7、ES8、ES9、ES10、ES11、ES12新特性大全!
共 27184字,需瀏覽 55分鐘
·
2024-06-28 12:57
作者:南殤
https://juejin.cn/post/7243677232827891773
ES7
ES2016(ES7)中新增了如下特性??
-
Array.prototype.includes -
Exponentiation Operator
一、Array.prototype.includes
1.1 定義
includes()方法用來判斷一個(gè)數(shù)組或字符串中是否包含一個(gè)指定的值
返回值: 如果包含返回true,否則返回false。
1.2 語法
-
arr.includes(valueToFind) -
arr.includes(valueToFind, fromIndex)
let arr = [1, 2, 3, 4];
arr.includes(3); // true
arr.includes(5); // false
arr.includes(3, 1); // true
1.2.1 fromIndex大于等于數(shù)組長度
返回false
arr.includes(3, 3); // false
arr.includes(3, 20); // false
1.2.2 計(jì)算出的索引小于0
如果fromIndex為負(fù)值,使用數(shù)組長度 + fromIndex計(jì)算出的索引作為新的fromIndex,如果新的fromIndex為負(fù)值,則搜索整個(gè)數(shù)組。
arr.includes(3, -100); // true
arr.includes(3, -1); // false
二、Exponentiation Operator冪運(yùn)算
冪運(yùn)算符**,相當(dāng)于Math.pow()
5 ** 2 // 25
Math.pow(5, 2) // 25
ES8
ES2017(ES8)新增了以下特性??
-
Async functions -
Object.entries -
Object.values -
Object.getOwnPropertyDescriptors -
Trailing commas
一、Async functions
1.1 定義
Async functions 是 async 聲明的函數(shù),async 函數(shù)是 AsyncFunction 構(gòu)造函數(shù)的實(shí)例,其中允許使用 await 關(guān)鍵字。
1.2 語法
async function name([param[, param[, ...param]]]) {
// statements
}
1.3 返回值
一個(gè)Promise
1.4 例子
const promise = () => {
console.log('1');
return new Promise((resolve, reject) => {
resolve('2');
});
};
const asyncFun = async() => {
console.log('3');
const test = await promise();
console.log('4', test);
}
asyncFun(); // 3 1 4 2
二、Object.entries
2.1 返回值
Object.entries()方法返回一個(gè)給定對(duì)象自身可枚舉屬性的鍵值對(duì)數(shù)組
2.2 語法
Object.entries(obj);
2.3 例子
let obj = {a: 1, b: 2};
Object.entries(obj); // [['a', 1], ['b', 2]]
三、Object.values
3.1 返回值
Object.values()方法返回一個(gè)給定對(duì)象自身可枚舉屬性值的數(shù)組
3.2 語法
Object.values(obj);
3.3 例子
let obj = {a: 1, b: 2};
Object.values(obj); // [1, 2]
四、Object.getOwnPropertyDescriptors
4.1 返回值
Object.getOwnPropertyDescriptors() 方法用來獲取一個(gè)對(duì)象的所有自身屬性的描述符
4.2 語法
Object.getOwnPropertyDescriptors(obj);
4.3 例子
let obj = {a: 1, b: 2};
Object.getOwnPropertyDescriptors(obj); // [a: {configurable: true, enumerable: true, value: 1, writable: true}, b: {configurable: true, enumerable: true, value: 2, writable: true}]
五、Trailing commas 尾后逗號(hào)
5.1 定義
如果你想要添加新的屬性,并且在上一行已經(jīng)使用了尾后逗號(hào),你可以僅僅添加新的一行,而不需要修改上一行
5.2 注意
-
JSON 不允許尾后逗號(hào)
5.3 舉例
-
字面量中的尾后逗號(hào)
a: 1,b: 2}
- 數(shù)組
```js
let arr = [
1,
2
] -
對(duì)象 let obj = { -
函數(shù)中的尾后逗號(hào)
-
參數(shù)定義
function(x, y) {}
function(x, y,) {}
(x, y) => {}
(x, y,) => {} -
函數(shù)調(diào)用
fun(x, y)
fun(x, y,) -
不合法的尾后逗號(hào)
不含參數(shù)或者在剩余參數(shù)后面加逗號(hào),都是不合法的尾后逗號(hào)
function(,) {}
(,) => {}
fn(,)
function(...arg,) {}
(...arg,) => {} -
解構(gòu)中的尾后逗號(hào)
let [a, b,] = [1, 2];
let {x, y} = {x: 1, y: 2}; -
JSON中的尾后逗號(hào)
JSON中不允許出現(xiàn)尾后逗號(hào)
JSON.parse("[1, 2, 3,]") // ?
JSON.parse('{"a": 1,}') // ?
JSON.parse("[1, 2, 3]") // ?
JSON.parse('{"a": 1}') // ?
六、String.prototype.padStart()
6.1 定義
padStart() 用另一個(gè)字符串填充當(dāng)前字符串。
6.2 返回值
在原字符串開頭填充指定的填充字符串直到目標(biāo)長度所形成的新字符串。
6.3 語法
str.padStart(targetLength);
str.padStart(targetLength, padString);
-
targetLength:當(dāng)前字符串需要填充到的目標(biāo)長度。如果這個(gè)數(shù)值小于當(dāng)前字符串的長度,則返回當(dāng)前字符串本身。 -
padString(可選):填充字符串。如果字符串太長,使填充后的字符串長度超過了目標(biāo)長度,則只保留最左側(cè)的部分,其他部分會(huì)被截?cái)唷4藚?shù)的默認(rèn)值為 " "。
6.4 例子
'abc'.padStart(10); // " abc"
'abc'.padStart(10, "foo"); // "foofoofabc"
'abc'.padStart(6,"123465"); // "123abc"
'abc'.padStart(8, "0"); // "00000abc"
'abc'.padStart(1); // "abc"
七、String.prototype.padEnd()
7.1 定義
padEnd() 方法會(huì)用一個(gè)字符串填充當(dāng)前字符串(如果需要的話則重復(fù)填充)。
7.2 返回值
返回在原字符串末尾填充指定的填充字符串直到目標(biāo)長度所形成的新字符串。
7.3 語法
str.padEnd(targetLength)
str.padEnd(targetLength, padString)
-
targetLength:當(dāng)前字符串需要填充到的目標(biāo)長度。如果這個(gè)數(shù)值小于當(dāng)前字符串的長度,則返回當(dāng)前字符串本身。 -
padString(可選):填充字符串。如果字符串太長,使填充后的字符串長度超過了目標(biāo)長度,則只保留最左側(cè)的部分,其他部分會(huì)被截?cái)唷4藚?shù)的缺省值為 " "。
7.4 例子
'abc'.padEnd(10); // "abc "
'abc'.padEnd(10, "foo"); // "abcfoofoof"
'abc'.padEnd(6, "123456"); // "abc123"
'abc'.padEnd(1); // "abc"
ES9
ES2018(ES9)新增了如下特性??
-
Async iterators異步迭代器 -
Object rest properties剩余屬性 -
Object spread properties擴(kuò)展屬性 -
Promise.prototype.finally
一、Async iterators 異步迭代器
1.1 返回值
Async iterator 對(duì)象的 next() 方法返回一個(gè) Promise,這個(gè) Promise 的返回值可以被解析成 {value, done} 的格式,
1.2 語法
iterator.next().then(({value, done}) => {});
1.3 舉例
const asyncIterator = () => {
const array = [1, 2];
return {
next: function() {
if(array.length) {
return Promise.resolve({
value: array.shift(),
done: false
});
}
return Promise.resolve({
done: true
});
}
}
}
let iterator = asyncIterator();
const test = async() => {
await iterator.next().then(console.log); // {value: 1, done: false}
await iterator.next().then(console.log); // {value: 2, done: false}
await iterator.next().then(console.log); // {done: true}
}
test();
1.4 可以使用 for-await-of 在循環(huán)中異步調(diào)用函數(shù)
const promises = [
new Promise((resolve) => resolve(1)),
new Promise((resolve) => resolve(2)),
new Promise((resolve) => resolve(3)),
];
const test = async() => {
for await (const p of promises) {
console.log('p', p);
}
};
test();
二、Object rest properties
2.1 舉例
let test = {
a: 1,
b: 2,
c: 3,
d: 4
}
let {a, b, ...rest} = test;
console.log(a); // 1
console.log(b); // 2
console.log(rest); // {c: 3, d: 4}
2.2 注意
-
null不能使用擴(kuò)展運(yùn)算符
let {a, b, ...rest} = null; // ?
三、Object spread properties
3.1 舉例
let test = {
a: 1,
b: 2
}
let result = {c: 3, ...test};
console.log(result); // {c: 3, a: 1, b: 2}
let test = null;
let result = {c: 3, ...test}; // {c: 3}
四、Promise.prototype.finally
4.1 定義
在Promise結(jié)束的時(shí)候,不管是結(jié)果是resolved還是rejected,都會(huì)調(diào)用finally中的方法
finally中的回調(diào)函數(shù)不接受任何參數(shù)
4.2 返回值
一個(gè)Promise
4.3 語法
const promise = new Promise((resolve, reject) => {
resolve('resolved');
reject('rejectd');
})
promise.then((res) => {
console.log(res);
}).finally(() => {
console.log('finally')
});
4.4 舉例
const promise = new Promise((resolve, reject) => {
resolve(1);
reject(2);
});
const test = () => {
console.log(3);
promise.then((res) => {
console.log(4, res);
}).catch(err => {
console.log(5, err);
}).finally(() => {
console.log(6);
});
};
test(); // 3 4 1 6
ES10
ES2019(ES10)新增了如下新特性??:
-
Array.prototype.{flat, flatMap}扁平化嵌套數(shù)組 -
Object.fromEntries -
String.prototype.{trimStart, trimEnd} -
Symbol.prototype.description -
Optional catch binding -
Array.prototype.sort() is now required to be stable
一、Array.prototype.{flat, flatMap} 扁平化嵌套數(shù)組
1.1 Array.prototype.flat
1.1.1 定義
flat()方法會(huì)按照一個(gè)可指定的深度遍歷遞歸數(shù)組,并將所有元素與遍歷到的子數(shù)組中的元素合并為一個(gè)新數(shù)組返回。
1.1.2 語法
arr.flat([depth]);
-
depth是數(shù)組遍歷的深度,默認(rèn)是1。
1.1.3 返回值
一個(gè)新數(shù)組,不會(huì)改變舊數(shù)組。
1.1.4 舉例
const arr = [1, 2, [[[[3, 4]]]]];
arr.flat(); // [1, 2, [[[3, 4]]]]
arr.flat(3); // [1, 2, [3, 4]]
arr.flat(-1); // [1, 2, [[[[3, 4]]]]]
arr.flat(Infinity); // [1, 2, 3, 4]
1.1.5 注意
-
flat()會(huì)移除數(shù)組中的空項(xiàng)
let arr = [1, 2, , , 3];
arr.flat(); // [1, 2, 3]
1.1.6 替換
-
reduce與contact
let arr = [1, 2, [3, 4]];
arr.reduce((arr, val) => arr.concat(val), []);
-
...擴(kuò)展運(yùn)算符與contact
let arr = [1, 2, [3, 4]];
[].contact(...arr);
更多替換方式請(qǐng)查看 MDN ( https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/flat )
1.2 Array.prototype.flatMap
1.2.1 定義
flatMap()方法首先使用映射函數(shù)映射數(shù)組(深度值為1)的每個(gè)元素,然后將結(jié)果壓縮成一個(gè)新數(shù)組。
1.2.2 返回值
一個(gè)新數(shù)組,并且每個(gè)元素都是回調(diào)函數(shù)的結(jié)果。
1.2.3 語法
arr.flatMap(function callback(currentVal[, index[, array]]) {
}[, thisArg])
-
callback: 可以生成一個(gè)新數(shù)組所調(diào)用的函數(shù) -
currentVal: 當(dāng)前數(shù)組在處理的元素 -
index: 可選,正在處理的元素索引 -
array: 可選,被調(diào)用的數(shù)組 -
thisArg: 執(zhí)行callback函數(shù)時(shí)使用的this值
1.2.4 舉例
let arr = ['My name', 'is', '', 'Lisa'];
let newArr1 = arr.flatMap(cur => cur.split(' '));
let newArr2 = arr.map(cur => cur.split(' '));
console.log(newArr1); // ["My", "name", "is", "", "Lisa"]
console.log(newArr2); // [["My", "name"], ["is"], [""], ["Lisa"]]
二、Object.fromEntries
2.1 定義
fromEntries() 方法會(huì)把鍵值對(duì)列表轉(zhuǎn)換成一個(gè)對(duì)象
2.2 返回值
一個(gè)新的對(duì)象
2.3 語法
Object.fromEntries(iterable)
-
iterable: Array、Map等可迭代對(duì)象
2.4 舉例
let map = new Map([['a', 1], ['b', 2]]);
let mapToObj = Object.fromEntries(map);
console.log(mapToObj); // {a: 1, b: 2}
let arr = [['a', 1], ['b', 2]];
let arrToObj = Object.fromEntries(arr);
console.log(arrToObj); // {a: 1, b: 2}
let obj = {a: 1, b: 2};
let newObj = Object.fromEntries(
Object.entries(obj).map(
([key, val]) => [key, val * 2]
)
);
console.log(newObj); // {a: 2, b: 4}
三、String.prototype.{trimStart, trimEnd}
3.1 String.prototype.trimStart
3.1.1 定義
trimStart() 方法用來刪除字符串的開頭的空白字符。
trimLeft() 是它的別名。
3.1.2 返回值
一個(gè)新的字符串,這個(gè)字符串左邊的空格已經(jīng)被去除掉了。
3.1.3 語法
str.trimStart();
str.trimLeft();
3.1.4 ?? 舉例
let str = ' a b cd ';
str.trimStart(); // 'a b cd '
str.trimLeft(); // 'a b cd '
3.2 String.prototype.trimEnd
3.2.1 定義
trimEnd() 方法用來刪除字符串末尾的空白字符。 trimRight() 是它的別名
3.2.2 返回值
一個(gè)新的字符串,這個(gè)字符串右邊的空格已經(jīng)被去除了
3.2.3 語法
str.trimEnd()
str.trimRight()
3.2.4 舉例
let str = ' a b cd ';
str.trimEnd(); // ' a b cd'
str.trimRight(); // ' a b cd'
四、Symbol.prototype.description
4.1 定義
description 是一個(gè)只讀屬性
4.2 返回值
它返回Symbol對(duì)象的可選描述的字符串
4.3 語法
Symbol('myDescription').description;
Symbol.iterator.description;
Symbol.for('foo').description;
4.4 舉例
Symbol('foo').description; // 'foo'
Symbol().description; // undefined
Symbol.for('foo').description; // 'foo'
五、Optional catch binding
可選的捕獲綁定,允許省略catch綁定和它后面的圓括號(hào)
以前的用法:
try {
} catch(err) {
console.log('err', err);
}
ES10 的用法:
try {
} catch {
}
六、JSON.stringify() 的增強(qiáng)力
JSON.stringify() 在 ES10 修復(fù)了對(duì)于一些超出范圍的 Unicode 展示錯(cuò)誤的問題,所以遇到 0xD800-0xDFF 之內(nèi)的字符會(huì)因?yàn)闊o法編碼成 UTF-8 進(jìn)而導(dǎo)致顯示錯(cuò)誤。在 ES10 它會(huì)用轉(zhuǎn)義字符的方式來處理這部分字符而非編碼的方式,這樣就會(huì)正常顯示了。
JSON.stringify('??'); // '"??"'
七、修訂 Function.prototype.toString()
以前的 toString 方法來自 Object.prototype.toString(),現(xiàn)在 的 Function.prototype.toString() 方法返回一個(gè)表示當(dāng)前函數(shù)源代碼的字符串。以前只會(huì)返回這個(gè)函數(shù),不會(huì)包含空格、注釋等。
function foo() {
// es10新特性
console.log('imooc')
}
console.log(foo.toString());
// function foo() {
// // es10新特性
// console.log('imooc')
// }
ES11
ES2020(ES11)新增了如下新特性??:
-
空值合并運(yùn)算符(Nullish coalescing Operator) -
可選鏈 Optional chaining -
globalThis -
BigInt -
String.prototype.matchAll() -
Promise.allSettled() -
Dynamic import(按需 import)
一、空值合并運(yùn)算符(Nullish coalescing Operator)
1.1 空值合并操作符(??)
空值合并操作符(??)是一個(gè)邏輯操作符,當(dāng)左邊的操作數(shù)為 null 或 undefined 的時(shí)候,返回其右側(cè)操作符,否則返回左側(cè)操作符。
undefined ?? 'foo' // 'foo'
null ?? 'foo' // 'foo'
'foo' ?? 'bar' // 'foo'
1.2 邏輯或操作符(||)
邏輯或操作符(||),會(huì)在左側(cè)操作數(shù)為假值時(shí)返回右側(cè)操作數(shù),也就是說如果使用 || 來為某些變量設(shè)置默認(rèn)值,可能會(huì)出現(xiàn)意料之外的情況。比如 0、''、NaN、false:
0 || 1 // 1
0 ?? 1 // 0
'' || 'bar' // 'bar'
'' ?? 'bar' // ''
NaN || 1 // 1
NaN ?? 1 // NaN
false || 'bar' // 'bar'
false ?? 'bar' // false
1.3 注意
不可以將 ?? 與 AND(&&)OR(||)一起使用,會(huì)報(bào)錯(cuò)。
null || undefined ?? "foo"; // 拋出 SyntaxError
true || undefined ?? "foo"; // 拋出 SyntaxError
二、可選鏈 Optional chaining
2.1 介紹
可選鏈操作符(?.)允許讀取位于連接對(duì)象鏈深處的屬性的值,而不必明確驗(yàn)證鏈中的每個(gè)引用都是否有效。?. 操作符的功能類似于.鏈?zhǔn)讲僮鞣煌幵谟冢谝脼?null 或 undefined 時(shí)不會(huì)報(bào)錯(cuò),該鏈路表達(dá)式返回值為 undefined。
以前的寫法:
const street = user && user.address && user.address.street;
const num = user && user.address && user.address.getNum && user.address.getNum();
console.log(street, num);
ES11 的寫法:
const street2 = user?.address?.street;
const num2 = user?.address?.getNum?.();
console.log(street2, num2);
2.2 注意
可選鏈不能用于賦值:
let object = {};
object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignment
三、globalThis
以前,在 Web 中,可以通過 window、self 取到全局對(duì)象,在 node.js 中,必須使用 global。
在松散模式下,可以在函數(shù)中返回 this 來獲取全局對(duì)象,但是在嚴(yán)格模式和模塊環(huán)境下,this 會(huì)返回 undefined。
以前要獲取全局對(duì)象,可以定義一個(gè)函數(shù):
const getGlobal = () => {
if (typeof self !== 'undefined') {
return self
}
if (typeof window !== 'undefined') {
return window
}
if (typeof global !== 'undefined') {
return global
}
throw new Error('無法找到全局對(duì)象')
}
const globals = getGlobal()
console.log(globals)
現(xiàn)在 globalThis 提供了一個(gè)標(biāo)準(zhǔn)的方式來獲取不同環(huán)境下的全局對(duì)象自身值。
四、BigInt
BigInt 是一種內(nèi)置對(duì)象,用來創(chuàng)建比 2^53 - 1(Number 可創(chuàng)建的最大數(shù)字) 更大的整數(shù)。可以用來表示任意大的整數(shù)
4.1 如何定義一個(gè) BigInt
-
在一個(gè)整數(shù)字面量后面加 n,例如 10n -
調(diào)用函數(shù) BigInt()并傳遞一個(gè)整數(shù)值或字符串值,例如BigInt(10)
4.2 BigInt 的特點(diǎn)
-
BigInt 不能用于 Math 對(duì)象中的方法; -
BigInt 不能與任何 Number 實(shí)例混合運(yùn)算,兩者必須轉(zhuǎn)換成同一種類型。但是需要注意,BigInt 在轉(zhuǎn)換成 Number 時(shí)可能會(huì)丟失精度。 -
當(dāng)使用 BigInt 時(shí),帶小數(shù)的運(yùn)算會(huì)被向下取整 -
BigInt 和 Number 不是嚴(yán)格相等,但是寬松相等 0n === 0 // false
0n == 0 // true -
BigInt 和 Number 可以比較 2n > 2 // false
2n > 1 // true -
BigInt 和 Number 可以混在一個(gè)數(shù)組中排序 const mixed = [4n, 6, -12n, 10, 4, 0, 0n];
mixed.sort(); // [-12n, 0, 0n, 10, 4n, 4, 6] -
被 Object 包裝的 BigInt 使用 object 的比較規(guī)則進(jìn)行比較,只用同一個(gè)對(duì)象比較時(shí)才相等 0n === Object(0n); // false
Object(0n) === Object(0n); // false
const o = Object(0n);
o === o // true
4.3 BigInt 的方法
4.3.1 BigInt.asIntN()
將 BigInt 值轉(zhuǎn)換為一個(gè) -2^(width-1) 與 2^(width-1) - 1 之間的有符號(hào)整數(shù)。
4.3.2 BigInt.asUintN()
將一個(gè) BigInt 值轉(zhuǎn)換為 0 與 2^(width) - 1 之間的無符號(hào)整數(shù)。
4.3.3 BigInt.prototype.toLocaleString()
返回此數(shù)字的 language-sensitive 形式的字符串。覆蓋 Object.prototype.toLocaleString() 方法。
4.3.4 BigInt.prototype.toString()
返回以指定基數(shù) (base) 表示指定數(shù)字的字符串。覆蓋 Object.prototype.toString() 方法。
4.3.5 BigInt.prototype.valueOf()
返回指定對(duì)象的基元值。覆蓋 Object.prototype.valueOf() 方法。
五、String.prototype.matchAll()
返回一個(gè)包含所有匹配正則表達(dá)式的結(jié)果及分組捕獲組的迭代器。
const regexp = /t(e)(st(d?))/g;
const str = 'test1test2';
const array = [...str.matchAll(regexp)];
console.log(array[0]); // ["test1", "e", "st1", "1"]
console.log(array[1]); // ["test2", "e", "st2", "2"]
六、Promise.allSettled()
類方法,返回一個(gè)在所有給定的 promise 都已經(jīng) fulfilled 或 rejected 后的 promise,并帶有一個(gè)對(duì)象數(shù)組,每個(gè)對(duì)象表示對(duì)應(yīng)的 promise 結(jié)果。
Promise.allSettled([
Promise.resolve(33),
new Promise((resolve) => setTimeout(() => resolve(66), 0)),
99,
Promise.reject(new Error("an error")),
]).then((values) => console.log(values));
// [
// { status: 'fulfilled', value: 33 },
// { status: 'fulfilled', value: 66 },
// { status: 'fulfilled', value: 99 },
// { status: 'rejected', reason: Error: an error }
// ]
七、Dynamic import(按需 import)
import 可以在需要的時(shí)候,再加載某個(gè)模塊。
button.addEventListener('click', event => {
import('./dialogBox.js')
.then(dialogBox => {
dialogBox.open();
})
.catch(error => {
/* Error handling */
})
});
ES12
ES 2021(ES12)新增了如下新特性??:
-
邏輯運(yùn)算符和賦值表達(dá)式(&&=,||=,??=) -
String.prototype.replaceAll() -
數(shù)字分隔符 -
Promise.any
一、邏輯運(yùn)算符和賦值表達(dá)式(&&=,||=,??=)
1.1 &&=
邏輯與賦值運(yùn)算符 x &&= y 等價(jià)于 x && (x=y):意思是當(dāng) x 為真時(shí),x = y。
let a = 1;
let b = 0;
a &&= 2;
console.log(a); // 2
b &&= 2;
console.log(b); // 0
1.2 ||=
邏輯或賦值運(yùn)算符 x ||= y 等價(jià)于 x || (x = y):意思是僅在 x 為 false 的時(shí)候,x = y。
const a = { duration: 50, title: '' };
a.duration ||= 10;
console.log(a.duration); // 50
a.title ||= 'title is empty.';
console.log(a.title); // "title is empty"
1.3 ??=
邏輯空賦值運(yùn)算符 x ??= y 等價(jià)于 x ?? (x = y):意思是僅在 x 為 null 或 undefined 的時(shí)候,x = y。
const a = { duration: 50 };
a.duration ??= 10;
console.log(a.duration); // 50
a.speed ??= 25;
console.log(a.speed); // 25
二、String.prototype.replaceAll()
返回一個(gè)新字符串,字符串中所有滿足 pattern 的部分都會(huì)被 replacement 替換掉。原字符串保持不變。
-
pattern 可以是一個(gè)字符串或 RegExp; -
replacement 可以是一個(gè)字符串或一個(gè)在每次被匹配被調(diào)用的函數(shù)。
'aabbcc'.replaceAll('b', '.'); // 'aa..cc'
使用正則表達(dá)式搜索值時(shí),必須是全局的:
'aabbcc'.replaceAll(/b/, '.'); // TypeError: replaceAll must be called with a global RegExp
'aabbcc'.replaceAll(/b/g, '.'); // "aa..cc"
三、數(shù)字分隔符
ES12 允許 JavaScript 的數(shù)值使用下劃線(_)作為分隔符,但是沒有規(guī)定間隔的位數(shù):
123_00
小數(shù)和科學(xué)記數(shù)法也可以使用分隔符:
0.1_23
1e10_00
?? 注意:
-
不能放在數(shù)值的最前面和最后面; -
不能將兩個(gè)及兩個(gè)以上的分隔符連在一起; -
小數(shù)點(diǎn)的前后不能有分隔符; -
科學(xué)記數(shù)法里,e 或 E 前后不能有分隔符。
四、Promise.any
方法接受一組 Promise 實(shí)例作為參數(shù),包裝成一個(gè)新的 Promise 實(shí)例返回。
只要參數(shù)實(shí)例有一個(gè)變成 fulfilled 狀態(tài),包裝實(shí)例就會(huì)變成 fulfilled 狀態(tài);如果所有參數(shù)實(shí)例都變成 rejected 狀態(tài),包裝實(shí)例就會(huì)變成 rejected 狀態(tài)。
const promise1 = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("promise1");
// reject("error promise1 ");
}, 3000);
});
};
const promise2 = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("promise2");
// reject("error promise2 ");
}, 1000);
});
};
const promise3 = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("promise3");
// reject("error promise3 ");
}, 2000);
});
};
Promise.any([promise1(), promise2(), promise3()])
.then((first) => {
// 只要有一個(gè)請(qǐng)求成功 就會(huì)返回第一個(gè)請(qǐng)求成功的
console.log(first); // 會(huì)返回promise2
})
.catch((error) => {
// 所有三個(gè)全部請(qǐng)求失敗 才會(huì)來到這里
console.log("error", error);
});
Promise.any([promise1(), promise2(), promise3()])
.then((first) => {
// 只要有一個(gè)請(qǐng)求成功 就會(huì)返回第一個(gè)請(qǐng)求成功的
console.log(first); // 會(huì)返回promise2
})
.catch((error) => {
// 所有三個(gè)全部請(qǐng)求失敗 才會(huì)來到這里
console.log("error", error);
});
