Array.flat() 递归地将嵌套数组展平到指定的深度。默认值为1
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()
const arr1 = [1, 2, 3];
arr1.map(x => [x * 4]); // [[4], [8], [12]]
arr1.flatMap(x => [x * 4]); // [4, 8, 12]
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.trimStart()、String.trimEnd()字符串两边删除空格
const test = " hello ";
test.trim(); // "hello";
test.trimStart(); // "hello ";
test.trimEnd(); // " hello";
Object.fromEntries 将键值对列表转换为对象
const obj = { prop1: 2, prop2: 10, prop3: 15 };
//将对象转换为数组
let array = Object.entries(obj); // [["prop1", 2], ["prop2", 10], ["prop3", 15]]
//简单改变数值
array = array.map(([key, value]) => [key, Math.pow(value, 2)]); // [["prop1", 4], ["prop2", 100], ["prop3", 225]]
//将数组转换回对象
const newObj = Object.fromEntries(array); // {prop1: 4, prop2: 100, prop3: 225}
可选的Catch Binding
try {
//...} catch (er) {
//handle error with parameter er}
try {
//...} catch {
//handle error without parameter}
Symbol.description
const testSymbol = Symbol("Desc");
testSymbol.description; // "Desc"
Function.toString() 会完全按照定义的方式返回函数,包括空格和注释
//之前:
function /* foo comment */ foo() {}
foo.toString(); // "function foo() {}"
//现在是:
foo.toString(); // "function /* foo comment */ foo() {}"
JSON.parse()改进
行分隔符(\ u2028)和段落分隔符(\ u2029)符号正确解析,而不是导致SyntaxError。