ES10 可以使用几个新特性

在JavaScript中,将数据从一种格式转换为另一种格式非常常见。

Object.entrie()方法

为了便于将对象转换为数组,ES2017引入了Object.entrie()方法。 此方法将对象作为参数,并以[key,value]的形式返回对象自己的可枚举字符串键控属性对的数组。 例如:

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

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

Object.fromEntries()方法

此静态方法允许你轻松地将键值对列表转换为对象:

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

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

这个方法主要是针对,一维数组,多维数据需要另想办法。

trimStart() and trimEnd()

trimStart()和trimEnd()方法在实现与trimLeft()和trimRight()相同。这些方法目前处于第4阶段,将被添加到规范中,以便与padStart()和padEnd()保持一致,来看一些例子:

const str = "   string   ";

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

// 相同结果
console.log(str.trimLeft());     // => "string   "
console.log(str.trimRight());    // => "   string"

flat() and flatMap()

flat() 方法可以将多维数组展平成一维数组

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

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

如果提供的数组中有空值,它们会被丢弃:

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]

数组将被展平的深度级别为1.如果要从结果中删除项目,只需返回一个空数组:

const arr = [[7.1], [8.1], [9.1], [10.1], [11.1]];

// do not include items bigger than 9
arr.flatMap(value => {
  if (value >= 10) {
    return [];
  } else {
    return Math.round(value);
  }
});  

// returns:
// => [7, 8, 9]

可选的 catch

以前的写法

try {
  // 使用浏览器可能尚未实现的功能
} catch (unused) {
  // 这里回调函数中已经帮我们处理好的错误
}

此代码中的catch回调的信息并没有用处。 但这样写是为了避免SyntaxError错误。 ES2019可以省略catch周围的括号:

try {
 // ...
} catch {
 // ....
}

猜你喜欢

转载自blog.csdn.net/qq_24147051/article/details/93601994