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

相关文章
相关标签/搜索