ES6+

ES2019

Array

Array.flat()

可将多层数组扁平化,默认深度为 1,若想获得完全扁平化数组,可传入 Infinity

1
2
3
4
5
6
7
8
9
10
11
12
13
const arr1 = [1, 2, [3, 4]];
arr1.flat(); // [1, 2, 3, 4]

const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat(2); // [1, 2, 3, 4, 5, 6]

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


// 如果数组中含有空元素将被移除
const arr4 = [1, 2, , 4, 5];
arr4.flat(); // [1, 2, 4, 5]

Array.flatMap()

相当于调用一次 map 函数,再将每个元素做一次深度为 1flat()

1
2
3
4
const sentence = ["This is a", "regular", "sentence"];

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

String

String.trimStart() and String.trimEnd()

作用分别为:去除开头的空格和末尾的空格

1
2
3
4
5
const test = " hello ";

test.trim(); // "hello";
test.trimStart(); // "hello ";
test.trimEnd(); // " hello";

Object

Object.fromEntries

我们可以使用 Object.Entries,将一个对象转化为 [key, value] 形式子元素组成的数组,以方便数据的操作。现在我们可以用 Object.fromEntries 再将这种形式的数组转化为对象:

1
2
3
4
5
6
7
8
9
const obj = { prop1: 2, prop2: 10, prop3: 15 };

let array = Object.entries(obj); // [["prop1", 2], ["prop2", 10], ["prop3", 15]]

// Let’s square the values of the new list of key-value pairs with a simple map:
array = array.map(([key, value]) => [key, Math.pow(value, 2)]); // [["prop1", 4], ["prop2", 100], ["prop3", 225]]

// Transforming the array back to an object
const newObj = Object.fromEntries(array); // {prop1: 4, prop2: 100, prop3: 225}

Function

Optional Catch Binding

可以不必传入 catch() 的参数:

1
2
3
4
5
6
7
8
9
10
11
try {
//...
} catch (er) {
//handle error with parameter er
}

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

Function.toString()

新的 Function.toString() 方法能够完整地返回函数定义时的一些如空格和注释等内容:

1
2
3
4
5
6
7
function /* foo comment */ foo() {}

// Before we had:
foo.toString(); // "function foo() {}"

// And now it’s:
foo.toString(); // "function /* foo comment */ foo() {}"

Symbol

Symbol.description

1
2
3
const testSymbol = Symbol("Desc");

testSymbol.description; // "Desc"