Array.flat(depth)
递归平铺多维数组,depth
指定嵌套数组中的结构深度,也就是指定的递归层级,默认是 1。此方法并不修改原数组,而是返回一个新的数组。
之前如果我们想平铺数组可以这样做:
1 | const flatten = arr => arr.reduce((flat, next) => flat.concat(Array.isArray(next) ? flatten(next) : next), []) |
或者利用展开运算符,但只适用于二维数组,不过可以通过递归平铺任意维度的数组:
1 | function flattenArray(arr) { |
现在我们可以直接使用:
1 | const arr1 = [1, 2, [3, 4]] |
如果数组中有空值,则会在平铺后移除:
1 | const arr4 = [1, 2, , 4, 5] |
Array.flatMap()
结合了map
方法和Array.flat()
方法,若map
返回多维数组,会对该数组进行depth
为 1 的平铺:
1 | const arr1 = [1, 2, 3] |
可以这样使用:
1 | const sentence = ['This is a', 'regular', 'sentence'] |
String.trimStart() 和 String.trimEnd()
已有的String.Trim()
会去除字符串前后的空格。而现在可以指定只移除一侧的空格:
1 | const test = 'hello' |
Object.fromEntries
将键值对数组转化为对象。是Object.Entries
的反操作:
1 | const obj = { prop1: 2, prop2: 10, prop3: 15 } |
Optional Catch Binding
可省略catch
的参数:
1 | try { |
Symbol.description
可通过新增的description
属性读取Symbol
的描述,在之前需要通过toString()
将Symbol
显式转为字符串:
1 | const testSymbol = Symbol('Desc') |
Function.toString()
返回表示函数源代码的字符串(包括空格和逗号)。之前调用该方法:
1 | function /* foo comment */ foo() {} |
现在的话:
1 | foo.toString(); // 'function /* foo comment */ foo() {}' |