26.ES10 新特性

 

1.Object.fromEntries()

Object.fromEntries() 方法可以将 二维数组 和 Map 转换成对象

(1) 二维数组

1
2
3
4
5
6
7
8
// 二维数组
const result = Object.fromEntries([
["name", "Tom"],
["age", 20],
["address", "street"]
]);
console.log(result);
// {name: 'Tom', age: 20, address: 'street'}

(2) Map

1
2
3
4
5
6
7
8
// Map
const m = new Map();
m.set("name", "Tom");
m.set("age", 20);
m.set("address", "street");
const result = Object.fromEntries(m);
console.log(result);
// {name: 'Tom', age: 20, address: 'street'}

(3) ES8 Object.entries()

Object.fromEntries()Object.entries() 互为逆运算

1
2
3
4
5
6
7
8
9
10
11
12
13
// Object.entries() ES8 特性
const arr = Object.entries({
name: "Tom",
age: 20,
address: "street"
});
console.log(arr);
// (3) [Array(2), Array(2), Array(2)]
// 0: (2) ['name', 'Tom']
// 1: (2) ['age', 20]
// 2: (2) ['address', 'street']
// length: 3
// [[Prototype]]: Array(0)

2.trimStart() 与 trimEnd()

1
2
trimStart(): 去除字符串左侧空格
trimEnd(): 去除字符串右侧空格
1
2
3
4
5
6
7
8
9
// trim
let str = " Hello world 123 ";

console.log(str.trim());
// Hello world 123
console.log(str.trimStart());
// Hello world 123
console.log(str.trimEnd());
// Hello world 123

3.flat() 与 flatMap()

(1) flat()

1
2
3
4
5
6
7
8
// flat()
// 将多维数组转换为低维数组
const arr1 = [1, 2, [3, 4], 5, [6, 7, 8], 9];
console.log(arr1.flat()); // (9) [1, 2, 3, 4, 5, 6, 7, 8, 9]

const arr2 = [1, 2, [3, 4, [5, 6, 7], 8], 9];
console.log(arr2.flat()); // (7) [1, 2, 3, 4, Array(3), 8, 9]
console.log(arr2.flat(2)); // (9) [1, 2, 3, 4, 5, 6, 7, 8, 9]

(2) flatMap()

1
2
3
const arr3 = [1, 2, 3, 4];
const result = arr3.map(item => item * 10);
console.log(result); // (4) [10, 20, 30, 40]
1
2
3
4
5
6
7
8
9
10
11
12
const arr3 = [1, 2, 3, 4];
const result = arr3.map(function(item) {
return [item * 10];
});
console.log(result);
// (4) [Array(1), Array(1), Array(1), Array(1)]
// 0: [10]
// 1: [20]
// 2: [30]
// 3: [40]
// length: 4
// [[Prototype]]: Array(0)

使用 flatMap() 对元素进行展开

1
2
3
4
const arr4 = [1, 2, 3, 4];
const result = arr4.flatMap(item => [item * 10]);
console.log(result);
// (4) [10, 20, 30, 40]

4.Symbol.prototype.description

Symbol 对象的 description 属性值为 Symbol 对象的字符串的值

1
2
3
4
5
// 创建 Symbol 对象
let s = Symbol("SymbolTestObj");

console.log(s.description);
// SymbolTestObj