ES2019(ES10)

137 阅读1分钟

String.prototype.trimStart() / String.prototype.trimEnd()

const str = ' Hello world! ';
const trimBefore = str.trimStart() // 'Hello world! '
const trimAfter = str.trimEnd() // ' Hello world!'

Object.fromEntries()

把Object.entries()的结果反出来

const obj = { a: 1 }
const objEntries = Object.entries(obj) // [['a', 1]]
Object.fromEntries(objEntries) // { a: 1 }

Array.prototype.flat() / Array.prototype.flatMap()

const arr = [1, 2, [3, 4]];
arr.flat() // [1, 2, 3, 4]
// 参数可以控制层级
const arr2 = [1, 2, [3, [4, 5]]]
arr2.flat() // [1, 2, 3, [4, 5]]
arr2.flat(2) // [1, 2, 3, 4, 5]

[1, 2, [3, 4]].flatMap(v => {
  if (typeof v === 'number') {
    return v * 2
  } else {
    return v.map(v => v * 2)
  }
})
// [2, 4, 6, 8]

catch 的参数改为可选

try {
    return true;
} catch {
    return false;
}

Symbol.description

Symbol是es6中加入的新的基本数据类型,可以用来做对象的属性

const symbol = Symbol('This is a description');
const obj = {};
obj[symbol] = 'aaa';
// obj = {
//   Symbol(This is a Symbol): 'aaa'
// }
Symbol.description;  // 'This is a description'