ES2020新增功能
雙問號操作符
由於JavaScript是動態型別的,因此在分配變數時,我們需要牢記JavaScript對真值/假值的處理。 很多時候數字0和空字串''就是我們需要的值,我們來看一下下面這個物件
雙管道||
let player = {
profile: {
number: 0,
name: undefined,
other: ''
}
};
console.log(player.profile.number || "未知"); // 未知
console.log(player.profile.name || "未知"); // 未知
雙問號??
let player = {
profile: {
number: 0,
name: undefined,
other: ''
}
};
console.log(player.profile.number ?? "未知"); // 0
console.log(player.profile.name ?? "未知"); // 未知
很多情況下前端從後端獲取的資料中,並不確定某個屬性存不存在,所以會做個判斷,如果不存在就給個預設值避免報錯。
但是數字0和空字串''通常會被“誤傷”,比如nba球星威少、樂福、庫茲馬都是零號。
所以雙問號可以更準確得去處理null和undefined
可選操作符
在點號之前加一個問號
我太喜歡這個可選操作符了,和雙問號異曲同工,配合使用安全加倍。
相信前端遇到過很多次這種錯誤:
Cannot read property 'xxx' of undefined
有木有???!!!
有時候是粗心,有時候是拼錯屬性名,有時候就是後端資料返回有問題。
直接上程式碼:
很多時候會這樣處理,看上去沒什麼問題
// 假設從後端返回的是一個空物件
let player = {};
console.log(player.profile.number || "未知")
// Uncaught TypeError: Cannot read property 'number' of undefined
可選操作符,操作一下
let player = {};
console.log(player.profile.number ?? "23"); // player.profile is undefined`
console.log(player.profile?.number ?? "23"); //23
動態匯入
假設你有一個utils工具檔案,則其中某些功能可能很少使用,而匯入其所有依賴項會很浪費資源。現在,我們可以使用async/await在需要時動態匯入依賴項。
const add = (num1, num2) => num1 + num2;
export { add };
const doMath = async (num1, num2) => {
if (num1 && num2) {
const math = await import('./math.js');
console.log(math.add(5, 10));
};
};
doMath(4, 2);
我在現實專案中就遇到過,比如回帖編輯器,很多人只是看一下別人的回覆樂呵樂呵,使用者不點選回帖,就沒必要去載入整個editor.js
const replyBtn = document.querySelector('#replyBtn')
replyBtn.addEventListener('click', e => {
e.preventDefault()
(async () => {
const Editor = await import('./editor.js')
let editor = new Editor()
})();
})
// 也可以
replyBtn.addEventListener('click', e => {
e.preventDefault()
import('/modules/editor.js')
.then(Editor => {
let editor = new Editor()
})
.catch(err => {
console.log(err)
});
})
class的私有屬性
類的主要目的之一是將我們的程式碼包含在可重用的模組中。 我們可能會在很多地方用到這個類,有些屬性並不希望被類的外部訪問。
現在,通過在變數或函式前面新增一個簡單的雜湊符號,我們可以將它們完全保留給類內部使用。
class People {
#message = "湖人總冠軍"
bb() {
console.log(this.#message)
}
}
const p = new People()
p.bb() // 湖人總冠軍
console.log(p.#message) // Private name #message is not defined
廣州設計公司https://www.houdianzi.com 我的007辦公資源網站https://www.wode007.com
Promise.allSettled
當我們處理多個Promise時,尤其是當它們相互依賴時,通過Promise.allSettled可以很好的記錄除錯或者獲取每個promise的狀態結果,它會返回一個新的Promise,僅當傳遞給它的所有Promise都完成時(settled 顧名思義可以理解成定居、穩定)才返回。 這將使我們能夠訪問一個數組,其中包含每個promise的一些資料。
相比於Promise.all,如果傳入的promise中有一個失敗(rejected),Promise.all非同步地將失敗rejected的那個結果給失敗狀態的回撥函式,而不管其它promise是否完成。
Promise.allSettled會等所有傳入的promise的狀態變為fulfilled或者rejected
const p1 = new Promise((res, rej) => setTimeout(res, 1000, 24));
const p2 = new Promise((res, rej) => setTimeout(rej, 1000));
Promise.allSettled([p1, p2]).then(data => console.log(data));
// [
// Object { status: "fulfilled", value: 24},
// Object { status: "rejected", reason: undefined}
// ]