ES10新特性(2019)

183 阅读1分钟
Object.fromEntries()

会把键值对列表转换为一个对象,和ES8中新增的Object.entries()正好相对

Object.fromEntries(iterable);

iterable

let arr=[['a',1],['b',2],['c',3]]

console.log(Object.fromEntries(arr))  //{'a':1,'b':2,'c',3}
String.prototype.trimStart()

去掉字符串左边的空格 trimLeft()是此方法的别名

let a='   asd  sad  ';
a.trimLeft() //"asd  sad   "
a.trimStart() //"asd  sad   "
String.prototype.trimEnd()

去掉字符串右边的空格 trimRight()是此方法的别名

let a='   asd  sad  ';
a.trimRight() //"   asd  sad"
a.trimEnd() //"   asd  sad"
Array.prototype.flat()

拆分多维数组,返回拆分后的数组

var newArray = arr.flat([depth])

depth 可选

  • 指定要提取嵌套数组的结构深度,默认值为 1。
const arr = [1, [2, [3, [4, [5, [6, 7], 8], 9]]]];
console.log(arr.flat(1));
console.log(arr.flat(5));
console.log(arr.flat(Infinity));

// [1,2,[3, [4, [5, [6, 7], 8], 9]]]
// [1,2,3,4,5,6,7,8,9]
// [1,2,3,4,5,6,7,8,9]
Array.prototype.flatMap()

用于操作原数组中的每一项并且返回回来的数组会flat(1) 参数和map参数相同


let arr1 = ["it's Sunny in", "", "California"];

arr1.map(x => x.split(" "));
// [["it's","Sunny","in"],[""],["California"]]

arr1.flatMap(x => x.split(" "));
// ["it's","Sunny","in", "", "California"]
Symbool.prototype.description

是一个只读属性,它会返回 Symbol 对象的可选描述的字符串

    Symbol(123).description
    '123'
    Symbol('123').description
    '123'
    Symbol('asda').description
    'asda'
    Symbol.for('asda').description
    'asda'
Function.prototype.toString()

返回一个表示当前函数源代码的字符串

function test(str){
    return str+1
}
test.toString() //'function test(str){\n    return str+1\n}'
catch Building

ES10允许我们在捕获异常时省略参数(catch)

// es10以前
try {
  throw new Error();
} catch (error) {
  console.log("fail");
}

// es10
try {
  throw new Error();
} catch {
  console.log("fail");
}