ES2019 到來,5 個簡單 feature 瞭解下

翻譯:Taro28
原文:5 ES2019 features you can use todayjavascript

ECMAScript介紹:

ECMAScript 2015,一般咱們稱爲ES6,是過去六年最重要的更新,在這以後,負責開發ECMAScript標準的機構Technical Committee 39 (簡稱TC39)每一年都發布新標準。這個年度發佈週期簡化了不少流程,並使得新特性快速可用,受到Javascript社區的歡迎。java

今年即將發佈的ECMAScript2019(簡稱ES2019),新版本包括了 Object.fromEntries(), trimStart(), trimEnd(), flat(), flatMap(),symbol 對象的描述屬性、可選捕獲綁定等(最新版Firfox和Chrome已經實現)。git

1. Object.fromEntries()

在javascript中數據格式轉換是很常見的操做,轉換Objects到arrays,ES2017推薦使用Object.entries()方法。此方法入參object,返回object可enumerable的string-keyed屬性匹配的[key,value],例如:github

const obj = {one: 1, two: 2, three: 3};

console.log(Object.entries(obj));    
// => [["one", 1], ["two", 2], ["three", 3]]
複製代碼

但若是咱們想要逆轉操做,數組轉換成key-value匹配的object?其餘編程語言,如Python,提供了 dict() 函數實現,另外有Underscore.js和Lodash提供了 _.fromPairs 函數。web

ES2019推薦Object.fromEntries() 方法實現類似的功能。此靜態方法能夠很容易的實現一列key-value數組轉換成object:npm

const myArray = [['one', 1], ['two', 2], ['three', 3]];
const obj = Object.fromEntries(myArray);

console.log(obj);    // => {one: 1, two: 2, three: 3}
複製代碼

如上所述,Object.fromEntries() 很是簡單的實現了反轉 Object.entries() 操做。在這以前是很不簡單才能夠達到一樣的結果的:編程

const myArray = [['one', 1], ['two', 2], ['three', 3]];
const obj = Array.from(myArray).reduce((acc, [key, val]) => Object.assign(acc, {[key]: val}), {});

console.log(obj);    // => {one: 1, two: 2, three: 3}
複製代碼

須要注意的是 Object.fromEntries() 的入參能夠是任何具備可迭代屬性的對象,而且返回兩個元素的數組對象。Example:小程序

const map = new Map();
map.set('one', 1);
map.set('two', 2);

const obj = Object.fromEntries(map);

console.log(obj);    // => {one: 1, two: 2}
複製代碼

Object.fromEntries() 方法轉換objects一樣頗有用,以下面的代碼:數組

const obj = {a: 4, b: 9, c: 16};

// convert the object into an array
const arr = Object.entries(obj);

// get the square root of the numbers
const map = arr.map(([key, val]) => [key, Math.sqrt(val)]);

// convert the array back to an object
const obj2 = Object.fromEntries(map);

console.log(obj2);  // => {a: 2, b: 3, c: 4}
複製代碼

(譯者:直接for...of不就行了,殺雞用牛刀?)app

還有一個方便用途是在咱們須要處理url的query查詢參數時候(npm中的qs藥丸了):

const paramsString = 'param1=foo&param2=baz';
const searchParams = new URLSearchParams(paramsString);

Object.fromEntries(searchParams);    // => {param1: "foo", param2: "baz"}
//就不翻譯了,so easy
複製代碼

Object.fromEntries() 方法已經在stage 4(ECMAScript stage是什麼?參考知乎:精讀 TC39 與 ECMAScript 提案)建議中,這意味着即將包含在ES2019 standard中.

2. trimStart() 和 trimEnd()

trimStart()trimEnd() 方法從技術角度與 trimLeft()trimRight 類似,這些方法也已經在stage4建議中,而且將會與 padStart()padEnd() 具備一致標準:

const str = " string ";

// es2019
console.log(str.trimStart());    // => "string "
console.log(str.trimEnd());      // => " string"

// the same as
console.log(str.trimLeft());     // => "string "
console.log(str.trimRight());    // => " string"
複製代碼

考慮web兼容性問題,trimLeft()trimRight() 將會保留成爲 trimStart()trimEnd() 的別名。

3. flat() 和 flatMap()

flat() 把多維數組轉爲一維數組

const arr = ['a', 'b', ['c', 'd']];
const flattened = arr.flat();

console.log(flattened);    // => ["a", "b", "c", "d"]
複製代碼

在這以前,你可能須要使用 reduce()concat() 得到一維數組效果:

const arr = ['a', 'b', ['c', 'd']];
const flattened = [].concat.apply([], arr);

// or
// const flattened = [].concat(...arr);

console.log(flattened);    // => ["a", "b", "c", "d"]

複製代碼

Note 若是有多個空值在轉換的數組中,將會被丟棄:

const arr = ['a', , , 'b', ['c', 'd']];
const flattened = arr.flat();

console.log(flattened);    // => ["a", "b", "c", "d"]
複製代碼

flat() 接受一個可選的參數,用來指定解構嵌套層級數,默認值爲1:

const arr = [10, [20, [30]]];

console.log(arr.flat());     // => [10, 20, [30]]
console.log(arr.flat(1));    // => [10, 20, [30]]
console.log(arr.flat(2));    // => [10, 20, 30]
複製代碼

flatMap() 方法組合了 map()flat() 兩個方法功能,看例子吧:

const arr = [4.25, 19.99, 25.5];

console.log(arr.map(value => [Math.round(value)]));    
// => [[4], [20], [26]]

console.log(arr.flatMap(value => [Math.round(value)]));    
// => [4, 20, 26]

複製代碼

看出區別了嗎,就是組合map和去除嵌套層級 flat() 功能。默認解構一層嵌套層級。

4. Description property for Symbol objects

當建立一個Symbol對象時候,爲了方便調試,你能夠爲它增長一個描述。 ES2019提議中給Symbol Object增長了一個只讀描述屬性,舉個例子:

let sym = Symbol('foo');
console.log(sym.description);    // => foo

sym = Symbol();
console.log(sym.description);    // => undefined

// create a global symbol
sym = Symbol.for('bar');
console.log(sym.description);    // => bar
複製代碼

5. Optional catch binding

catch綁定 在try...catch方法塊中將不會被使用:

try {
  // use a feature that the browser might not have implemented
} catch (unused) {
  // fall back to an already implemented feature 
}
複製代碼

unused在這段代碼中並無被使用到(譯者:我相信大部分開發者都會如此).固然 咱們仍舊須要規避 SyntaxError 這類錯誤。這個提案對ECMAScript標準作了一個很小的改動:讓開發者忽略catch綁定和它的括號:

try {
  // use a feature that the browser might not have implemented
} catch {
  // do something that doesn’t care about the value thrown
}
複製代碼

END...

其餘推薦:

騰訊小姐姐的5分鐘幫助
小程序開源請求框架wxRequest

相關文章
相關標籤/搜索