做爲最流行的編程語言和最重要的 Web 開發語言之一,JavaScript 不斷演變,每次迭代都會獲得一些新的內部更新。讓咱們來看看 ES2019 有哪些新的特性,並加入到咱們平常開發中:javascript
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()
方法會移除數組中的空項:java
const arr4 = [1, 2, , 4, 5]; arr4.flat(); // [1, 2, 4, 5]
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.trim()
以外,如今還有單獨的方法,只能從每一端刪除空格:編程語言
const test = " hello "; test.trim(); // "hello"; test.trimStart(); // "hello "; test.trimEnd(); // " hello";
trimStart()
:別名 trimLeft()
,移除原字符串左端的連續空白符並返回,並不會直接修改原字符串自己。trimEnd()
:別名 trimRight()
,移除原字符串右端的連續空白符並返回,並不會直接修改原字符串自己。將鍵值對列表轉換爲 Object 的新方法。函數
它與已有 Object.entries() 正好相反,Object.entries()
方法在將對象轉換爲數組時使用,它返回一個給定對象自身可枚舉屬性的鍵值對數組。oop
但如今您能夠經過 Object.fromEntries
將操做的數組返回到對象中。post
下面是一個示例(將全部對象屬性的值平方):spa
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()
參數,由於在許多狀況下,您並不想使用它:
try { //... } catch (er) { //handle error with parameter er } try { //... } catch { //handle error without parameter }
description
是一個只讀屬性,它會返回 Symbol
對象的可選描述的字符串,用來代替 toString()
方法。
const testSymbol = Symbol("Desc"); testSymbol.description; // "Desc" testSymbol.toString(); // "Symbol(Desc)"
如今,在函數上調用 toString()
會返回函數,與它的定義徹底同樣,包括空格和註釋。
以前:
function /* foo comment */ foo() {} foo.toString(); // "function foo() {}"
如今:
foo.toString(); // "function /* foo comment */ foo() {}"
行分隔符 (u2028) 和段落分隔符 (u2029),如今被正確解析,而不是報一個語法錯誤。
var str = '{"name":"Bottle\u2028AnGe"}' JSON.parse(str) // {name: "Bottle AnGe"}
原文連接:JavaScript: What’s new in ES2019
走在最後,歡迎關注:前端瓶子君