格式良好的 `JSON.stringify`
JSON.stringify
之前的規範是當輸入包含任何孤立代理項時,返回格式不良的 Unicode 字串:
JSON.stringify('\uD800');
// → '"�"'
“格式良好的 JSON.stringify
”提案 修改了 JSON.stringify
,使其對孤立代理項輸出轉義序列,令其輸出有效 Unicode(並且可在 UTF-8 中表示):
JSON.stringify
之前的規範是當輸入包含任何孤立代理項時,返回格式不良的 Unicode 字串:
JSON.stringify('\uD800');
// → '"�"'
“格式良好的 JSON.stringify
”提案 修改了 JSON.stringify
,使其對孤立代理項輸出轉義序列,令其輸出有效 Unicode(並且可在 UTF-8 中表示):
BigInt
是 JavaScript 中一種新的數值型原始類型,能夠表示具有任意精度的整數。通過 BigInt
,您可以安全地存儲並操作超出數值類型安全整數範圍的大整數。本文通過一些使用案例,並將 BigInt
與 JavaScript 中的 Number
進行比較,來解釋 Chrome 67 中的新功能。
try
語句的 catch
子句以往需要一個綁定:
try {
doSomethingThatMightThrow();
} catch (exception) {
// ^^^^^^^^^
// 我們必須命名這個綁定,縱使我們不使用它!
handleException();
}
在 ES2019,catch
現在可以在沒有綁定的情況下使用。如果您在處理異常的代碼中不需要 exception
對象時,這很實用。
try {
doSomethingThatMightThrow();
} catch { // → 無綁定!
handleException();
}
catch
綁定支持ES2019 引入了 String.prototype.trimStart()
和 String.prototype.trimEnd()
:
const string = ' hello world ';
string.trimStart();
// → 'hello world '
string.trimEnd();
// → ' hello world'
string.trim(); // ES5
// → 'hello world'
此功能之前可以通過非標準的 trimLeft()
和 trimRight()
方法實現,這些方法仍然作為新方法的別名保留,從而保證向後兼容性。
const string = ' hello world ';
string.trimStart();
// → 'hello world '
string.trimLeft();
// → 'hello world '
string.trimEnd();
// → ' hello world'
string.trimRight();
// → ' hello world'
string.trim(); // ES5
// → 'hello world'
Function.prototype.toString()
現在返回源代码文本的準確片段,包括空格和註釋。以下是舊行為與新行為的比較示例:
動態 import()
引入了一種新的類函數形式的 import
,相較於靜態 import
解鎖了新的功能。本文比較了兩者並概述了新功能。
Promise.prototype.finally
讓您可以註冊一個回調函數,在 Promise 處於 處理完成 (即已解決或已拒絕)時被調用。
假設您想要獲取一些資料來顯示在頁面上。此外,您還希望在請求開始時顯示載入的旋轉圖標,而在請求完成時隱藏它。如果出現問題,則改為顯示錯誤訊息。
const fetchAndDisplay = ({ url, element }) => {
showLoadingSpinner();
fetch(url)
.then((response) => response.text())
.then((text) => {
element.textContent = text;
hideLoadingSpinner();
})
.catch((error) => {
element.textContent = error.message;
hideLoadingSpinner();
});
};
在討論 物件的剩餘與展開特性 之前,我們先回顧一下非常相似的一個功能。
早在 ECMAScript 2015 引入了用於陣列解構賦值的 剩餘元素 和用於陣列字面值的 展開元素。
// 陣列解構賦值中的剩餘元素:
const primes = [2, 3, 5, 7, 11];
const [first, second, ...rest] = primes;
console.log(first); // 2
console.log(second); // 3
console.log(rest); // [5, 7, 11]
// 陣列字面值中的展開元素:
const primesCopy = [first, second, ...rest];
console.log(primesCopy); // [2, 3, 5, 7, 11]
那麼有什麼新東西呢?一個提案使得物件字面值也可以使用剩餘與展開特性。
// 物件解構賦值中的剩餘特性:
const person = {
firstName: 'Sebastian',
lastName: 'Markbåge',
country: 'USA',
state: 'CA',
};
const { firstName, lastName, ...rest } = person;
console.log(firstName); // Sebastian
console.log(lastName); // Markbåge
console.log(rest); // { country: 'USA', state: 'CA' }