ES2019 到来,5 个简单 feature 了解下

991 阅读4分钟

翻译:Taro28
原文:5 ES2019 features you can use today

ECMAScript介绍:

ECMAScript 2015,通常我们称为ES6,是过去六年最重要的更新,在这之后,负责开发ECMAScript标准的机构Technical Committee 39 (简称TC39)每年都发布新标准。这个年度发布周期简化了很多流程,并使得新特性快速可用,受到Javascript社区的欢迎。

今年即将发布的ECMAScript2019(简称ES2019),新版本包括了 Object.fromEntries(), trimStart(), trimEnd(), flat(), flatMap(),symbol 对象的描述属性、可选捕获绑定等(最新版Firfox和Chrome已经实现)。

1. Object.fromEntries()

在javascript中数据格式转换是很常见的操作,转换Objects到arrays,ES2017推荐使用Object.entries()方法。此方法入参object,返回object可enumerable的string-keyed属性匹配的[key,value],例如:

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 函数。

ES2019推荐Object.fromEntries() 方法实现相似的功能。此静态方法可以很容易的实现一列key-value数组转换成object:

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不就好了,杀鸡用牛刀?)

还有一个方便用途是在我们需要处理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