js ES2019

Array.flat()

之前:

const arr = [1,2,[3,4,[5,6,[7,8]]]]
const flatten = (arr) => {
	let newArr = []
    arr.map(item => Array.isArray(item) ? (newArr = newArr.concat(flatten(item))) : newArr.push(item))
    return newArr;
}
flatten(arr) // [1, 2, 3, 4, 5, 6, 7, 8]

现在:

const arr = [1,2,[3,4,[5,6,[7,8]]]]
arr.flat() // [1,2,3,4,[5,6,[7,8]]]
arr.flat(1) // [1,2,3,4,[5,6,[7,8]]]
arr.flat(2) // [1,2,3,4,5,6,[7,8]]
arr.flat(Infinity) // [1, 2, 3, 4, 5, 6, 7, 8]

若数组中包含空元素,将会被移除

const arr = [1,2,,4,5]
arr.flat() //[1, 2, 4, 5]

Array.flatMap()

map() + flat() => flatmap()

例子1:

const arr = [1,2,3];
arr.map(item => [item*2]) // [[2],[4],[6]]
arr.flatMap(item => [item*2]) //[2,4,6]

例子2:

const sentence = ["This is a", "regular", "sentence"];
sentence.map(item => item.split(" ")) // [["This is a"],["regular"],["sentence"]]
sentence.flatMap(item => item.split(" ")) // ["This", "is", "a", "regular", "sentence"]

String.trimStart() and String.trimEnd()

const text = " hello world ";
text.trim() // "hello world"
text.trimStart() // 等同于 text.trimLeft(),输出结果:"hello world "
text.trimEnd() //  等同于 text.trimRight(),输出结果" hello world"

Object.fromEntries

const obj = { score1: 2, score2: 10, score3: 15 };
let arr = Object.entries(obj) // [["score1", 2], ["score2", 10], ["score3", 15]]
arr.map(([key, value]) => [key,value * 2]) // [["score1", 4], ["score2", 20], ["score3", 30]]
const newObj = Object.fromEntries(arr) // {score1: 4, score2: 20, score3: 30}

Optional Catch Binding

之前:

try {
  //...
} catch (er) {
  //handle error with parameter er
}

现在:

try {
  //...
} catch {
  //handle error without parameter
}

Symbol.description

之前:

const testSymbol = Symbol("Desc");
testSymbol.toString(); // "Symbol(Desc)"

现在:

const testSymbol = Symbol("Desc");
testSymbol.description; // "Desc"

Function.toString()

之前:

function /* foo comment */ foo() {}
foo.toString(); // "function foo() {}"

现在:

function /* foo comment */ foo() {}
foo.toString(); // "function /* foo comment */ foo() {}"

参考链接:
[1]、JavaScript: What’s new in ES2019
[2]、tc39/proposals

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值