作爲最流行的編程語言和最重要的 Web 開發語言之一,JavaScript 不斷演變,每次迭代都會得到一些新的內部更新。讓我們來看看 ES2019 有哪些新的特性,並加入到我們日常開發中:
Array.prototype.flat()
Array.prototype.flat()
遞歸地將嵌套數組拼合到指定深度。默認值爲 1,如果要全深度則使用 Infinity 。此方法不會修改原始數組,但會創建一個新數組:
-
const arr1 = [1, 2, [3, 4]];
-
arr1.flat();
-
// [1, 2, 3, 4]
-
const arr2 = [1, 2, [3, 4, [5, 6]]];
-
arr2.flat(2);
-
// [1, 2, 3, 4, 5, 6]
-
const arr3 = [1, 2, [3, 4, [5, 6, [7, 8]]]];
-
arr3.flat(Infinity);
-
// [1, 2, 3, 4, 5, 6, 7, 8]
flat()
方法會移除數組中的空項:
-
const arr4 = [1, 2, , 4, 5];
-
arr4.flat(); // [1, 2, 4, 5]
Array.prototype.flatMap()
flatMap()
方法首先使用映射函數映射每個元素,然後將結果壓縮成一個新數組。它與 Array.prototype.map
和 深度值爲 1的 Array.prototype.flat
幾乎相同,但 flatMap
通常在合併成一種方法的效率稍微高一些。
-
const arr1 = [1, 2, 3];
-
arr1.map(x => [x * 4]);
-
// [[4], [8], [12]]
-
arr1.flatMap(x => [x * 4]);
-
// [4, 8, 12]
更好的示例:
-
const sentence = ["This is a", "regular", "sentence"];
-
sentence.map(x => x.split(" "));
-
// [["This","is","a"],["regular"],["sentence"]]
-
sentence.flatMap(x => x.split(" "));
-
// ["This","is","a","regular", "sentence"]
-
// 可以使用 歸納(reduce) 與 合併(concat)實現相同的功能
-
sentence.reduce((acc, x) => acc.concat(x.split(" ")), []);
String.prototype.trimStart() 和 String.prototype.trimEnd()
除了能從字符串兩端刪除空白字符的 String.prototype.trim()
之外,現在還有單獨的方法,只能從每一端刪除空格:
-
const test = " hello ";
-
test.trim(); // "hello";
-
test.trimStart(); // "hello ";
-
test.trimEnd(); // " hello";
-
trimStart()
:別名trimLeft()
,移除原字符串左端的連續空白符並返回,並不會直接修改原字符串本身。 -
trimEnd()
:別名trimRight()
,移除原字符串右端的連續空白符並返回,並不會直接修改原字符串本身。
Object.fromEntries
將鍵值對列表轉換爲 Object 的新方法。
它與已有 Object.entries() 正好相反,Object.entries()
方法在將對象轉換爲數組時使用,它返回一個給定對象自身可枚舉屬性的鍵值對數組。
但現在您可以通過 Object.fromEntries
將操作的數組返回到對象中。
下面是一個示例(將所有對象屬性的值平方):
-
const obj = { prop1: 2, prop2: 10, prop3: 15 };
-
// 轉化爲鍵值對數組:
-
let array = Object.entries(obj);
-
// [["prop1", 2], ["prop2", 10], ["prop3", 15]]
將所有對象屬性的值平方:
-
array = array.map(([key, value]) => [key, Math.pow(value, 2)]);
-
// [["prop1", 4], ["prop2", 100], ["prop3", 225]]
我們將轉換後的數組 array
作爲參數傳入 Object.fromEntries ,將數組轉換成了一個對象:
-
const newObj = Object.fromEntries(array);
-
// {prop1: 4, prop2: 100, prop3: 225}
可選的 Catch 參數
新提案允許您完全省略 catch()
參數,因爲在許多情況下,您並不想使用它:
-
try {
-
//...
-
} catch (er) {
-
//handle error with parameter er
-
}
-
try {
-
//...
-
} catch {
-
//handle error without parameter
-
}
Symbol.description
description
是一個只讀屬性,它會返回 Symbol
對象的可選描述的字符串,用來代替 toString()
方法。
-
const testSymbol = Symbol("Desc");
-
testSymbol.description; // "Desc"
-
testSymbol.toString(); // "Symbol(Desc)"
Function.toString()
現在,在函數上調用 toString()
會返回函數,與它的定義完全一樣,包括空格和註釋。
之前:
-
function /* foo comment */ foo() {}
-
foo.toString(); // "function foo() {}"
現在:
foo.toString(); // "function /* foo comment */ foo() {}"
JSON.parse() 改進
行分隔符 (\u2028) 和段落分隔符 (\u2029),現在被正確解析,而不是報一個語法錯誤。
-
var str = '{"name":"Bottle\uAnGe"}'
-
JSON.parse(str)
-
// {name: "BottleAnGe"}
原文鏈接:https://blog.tildeloop.com/posts/javascript-what’s-new-in-es2019