JavaScript(JS)是最流行的編程語言之一,也是Web開發的主要語言之一,它在不斷髮展,每一次迭代都會帶來一些新的內部變化。讓我們來看看ES2019的一些新功能,它們可能很快就會進入我們的日常代碼:
Array.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]
如果你的數組中有一個空槽,它將被刪除:
const arr4 = [1, 2, , 4, 5];
arr4.flat(); // [1, 2, 4, 5]
Array.flatMap()
這是一個全新的方法,它結合了基本的map函數,然後使用新的Array.flat()方法將結果展平1個深度:
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"]
String.trimStart() and String.trimEnd()
除了同時刪除字符串兩邊的空格的String.Trim()之外,現在還出現了另一個方法只刪除字符串兩邊任意一邊的空格:
const test = " hello ";
test.trim(); // "hello";
test.trimStart(); // "hello ";
test.trimEnd(); // " hello";
Object.fromEntries
這是一個全新的方法:根據提供的鍵值對生成對象。它是我們熟悉的函數Object.Entries的逆向操作。(Object.Entries將對象轉換爲數組,以便更容易地進行操作。)在轉換之後,我們會得到一個數組,但是現在我們可以將調整過後的數組返回到一個對象中。讓我們試着用一個例子,我們想平方所有對象屬性的值:
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]]
我們已經轉換了對象值,但我們只剩下一個數組,這時候我們就需要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
我們現在可以任意訪問一個Symbol的description屬性,無需藉助toString()方法。
const testSymbol = Symbol("Desc");
testSymbol.description; // "Desc"
函數.toString ()
現在,我們對一個函數調用toString(),將完全按照定義的方式返回函數,包括空格和註釋。之前我們有:
function /* foo comment */ foo() {}
foo.toString(); // "function foo() {}"
然後現在是:
foo.toString(); // "function /* foo comment */ foo() {}"
JSON.parse()
現在,行分隔符 (\u2028) 和段落分隔符 (\u2029) 能被正確地解析,而不會導致SyntaxError。
希望本文能幫助到您!
看之後
點贊,讓更多的人也能看到這篇內容(收藏不點贊,都是耍流氓 -_-)
關注公衆號「新前端社區」,享受文章首發體驗!
每週重點攻克一個前端技術難點。