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