ES2020發(fā)布了新特性 https://github.com/tc39/proposals
新功能概覽
- 可選鏈運算符 - Optional Chaining
- 空值合并運算符 - Nullish coalescing Operator
- 標準化的全局對象 - globalThis
- Promise.allSettled
- String.prototype.matchAll
- BigInt
- for-in mechanics
- 異步加載模塊 - import()
詳細介紹
1. 可選鏈運算法
我們有時候為了訪問深層嵌套的屬性寓辱,一不小心就會報undefined
的錯纵搁,需要寫一個很長的&&
鏈去檢查每個屬性是否存在,代碼如下
let name = result && result.data && result.data.info && result.data.info.name;
如果不這么做南片,很可能會報程序異常 Uncaught TypeError: Cannot read property 'xxx' of undefined
,為了簡化上述的代碼肺素,ES2020新增了可選鏈運算符誊辉,就是在需要判斷是否存在的屬性后面加上?
耿戚,代碼如下:
let name = result?.data?.info?.name;
可選運算符也可以作用到方法上窒典,如下
let name = getUserInfo?.().data?.info?.name;
2.空值合并運算法 - Nullish coalescing Operator
獲取對象的屬性的時候蟆炊,我們經(jīng)常需要為null/undefined
的屬性設(shè)置默認值。現(xiàn)在我們都是使用||
運算符來處理瀑志,例如:
let userInfo = {};
let name = userInfo.name || 'Lucky';
但是涩搓,這么做會導(dǎo)致 false 、0 , ' '
等屬性值被覆蓋掉劈猪,導(dǎo)致運算結(jié)果不準確昧甘,為了避免這種情況,ES2020新增了 空值合并運算符 ??战得,代碼如下:
const result = {
data: {
nullValue: null,
numberValue: 0,
textValue: '',
booleanValue: false
}
};
const undefinedValue = result.data.undefinedValue ?? 'default value';
// 'default value'
const nullValue = result.data.nullValue ?? 'default value';
// 'default value'
const numberValue = result.data.numberValue ?? 200;
// 0
const textValue = result.data.textValue ?? 'default value';
// ''
const booleanValue = result.data.booleanValue ?? true;
// false
3. 標準化的全局對象-globalThis
Javascript在不同的環(huán)境中獲取全局對象的方式不同:
node: 通過 global;
瀏覽器:通過window充边、self等,甚至通過this常侦,但是this的指向比較復(fù)雜浇冰,依賴當(dāng)前的執(zhí)行上下文;
過去獲取全局對象,可通過下面的函數(shù):
const getGlobal = () => {
if (typeof self !== 'undefined') return self;
if (typeof window !== 'undefined') return window;
if (typeof global !== 'undefined') return global;
throw new Error('unable to locate global object');
}
const globals = getGlobal();
if (typeof globals.setTimeout !== 'function') {
// 此環(huán)境中沒有 setTimeout 方法聋亡!
}
ES2020提供的globalThis肘习,目的就是提供一種標準化方式訪問全局對象。上述的方法就可以直接改成
if (typeof globalThis.setTimeout !== 'function') {
// 此環(huán)境中沒有 setTimeout 方法坡倔!
}
4.Promise.allSettled
Promise.all
可以并發(fā)執(zhí)行多個任務(wù)漂佩,但是Promise.all有個缺陷脖含,那就是只要其中有一個任務(wù)出現(xiàn)異常了,就會直接進入catch的流程仅仆,所有任務(wù)都會掛掉器赞,這不是我們想要的。
const promise1 = new Promise((resolve) => setTimeout(resolve, 200, 'ok'));
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'bad'));
const promises = [promise1, promise2];
Promise.all(promises)
.then(result => {
// 不會觸發(fā)
})
.catch((err) => {
console.log(err); // bad
})
.finally(() => {
// 會觸發(fā)墓拜,獲取不到我們想要的內(nèi)容
})
這時候需要一個方法來保證如果一個任務(wù)失敗了港柜,其他任務(wù)還會繼續(xù)執(zhí)行,這樣才能最大限度的保障業(yè)務(wù)的可用性咳榜。
ES2020提供的Promise.allSettled
可以解決這個問題夏醉,Promise.allSettled
會返回一個promise,這個返回的promise會在所有輸入的promise resolve或reject之后觸發(fā)∮亢看代碼:
const promise1 = new Promise((resolve) => setTimeout(resolve, 200, 'ok'));
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'bad'));
const promises = [promise1, promise2];
Promise.allSettled(promises)
.then((results) => results.forEach((result) => console.log(result)));
// output:
// {status: "fulfilled", value: "ok"}
// {status: "rejected", reason: "bad"}
5. String.prototype.matchAll
我們先來看一下 String.prototype.match
const str = '<p>JS</p><p>正則表達式</p>';
const reg = /<\w+>(.*?)<\/\w+>/g;
console.log(str.match(reg));
// output: ['<p>JS</p>', '<p>正則表達式</p>']
可以看出返回的數(shù)組里包含了父匹配項畔柔,但未匹配到子項('JS'、'正則表達式')臣樱。
移除全局搜索符g
試試
const str = '<p>JS</p><p>正則表達式</p>';
const reg = /<\w+>(.*?)<\/\w+>/; // 這里把 g 去掉了
console.log(str.match(reg));
// output:
/*
["<p>JS</p>", "JS", index: 0, input: "<p>JS</p><p>正則表達式</p>", groups: undefined]
*/
這樣可以獲取到匹配的父項靶擦,包括子項,但只能獲取到一個滿足的匹配字符雇毫。
如何獲取到全局所有匹配項玄捕,包括子項呢?
ES2020提供了一種簡易的方式:String.prototype.matchAll
,該方法會返回一個迭代器棚放。
const str = '<p>JS</p><p>正則表達式</p>';
const reg = /<\w+>(.*?)<\/\w+>/g; // 這里是帶 g 的
const allMatches = str.matchAll(reg);
for (let item of allMatches) {
console.log(item);
}
/*
output:
第一次迭代:
[
"<p>JS</p>",
"JS",
index: 0,
input: "<p>JS</p><p>正則表達式</p>",
groups: undefined
]
第二次迭代:
[
"<p>正則表達式</p>",
"正則表達式",
index: 9,
input: "<p>JS</p><p>正則表達式</p>",
groups: undefined
]
*/
能看到每次迭代中可獲取所有的匹配枚粘,以及本次陪陪的成功的一些其他的信息。
6. BigInt
JS中Number類型只能安全的表示-(2^53-1)
至2^53-1
范圍的值飘蚯,即Number.MIN_SAFF_INTERGER 至 Number.MAX_SAFF_INTERGER,超出這個范圍的整數(shù)計算或者表示會丟失精度馍迄。
比如,我們在開發(fā)過程中局骤,有時候訂單id會特別長攀圈,返回到瀏覽器就會失去精度,只能用字符串來傳峦甩。
ES2020提供了一個新的數(shù)據(jù)類型:BigInt量承。使用BigInt有兩種方式:
- 在整數(shù)字面量后面加
n
let bigIntNum = 9007199254740993n;
- 使用
BigInt
函數(shù)
let bigIntNum = BigInt(9007199254740993);
通過BigInt,我們就可以安全的進行大數(shù)整型計算了穴店。
let big = 9007199254740994n + 9007199254740994n; // 結(jié)果為 18014398509481988n
注意:
BigInt 跟 number 不嚴格相等
0n === 0 //false
0n == 0 // true
BigInt不能跟number 一起運算
1n + 2
// VM8334:1 Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions...
不能使用+
把BigInt轉(zhuǎn)化成number
+1n
// TypeError: Cannot convert a BigInt value to a number
Number(1n)
// 1
7. for-in mechanics
之前在不同的引擎下for int循環(huán)出來的內(nèi)容順序可能是不一樣的,現(xiàn)在標準化了拿穴。
8. 異步加載模塊 - import()
有時候我們需要動態(tài)加載一些模塊泣洞,這時候就可以使用ES2020提供的import()
了
// utils.js
export default {
test: function () {
console.log('test')
}
}
// index.js
import('./utils.js')
.then((module) => {
module.default.test();
})
后記
項目中使用ES2020,只需要在babel配置文件中添加
{
"presets": ["es2020"]
}
參考資料
https://github.com/tc39/proposals/blob/master/finished-proposals.md
https://zhuanlan.zhihu.com/p/100251213