作為最流行的編程語言和最重要的 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]]將所有對象屬性的值平方:
新聞熱點
疑難解答
圖片精選