JavaScript Array flat() 方法介绍
ES2019 引入了 Array.prototype.flat() 方法,该方法创建一个新数组,其中子数组的所有元素递归连接到指定深度。
下面显示了 flat() 方法的语法:
let newArray = arrayObject.flat([depth])
depth 参数指定该方法使数组结构平坦的深度,它默认为 1。
下面的例子展示了如何扁平化一个数字数组:
const numbers = [1, 2, [3, 4, 5]];
const flatNumbers = numbers.flat();
console.log(flatNumbers);
输出:
[1, 2, 3, 4, 5]
在这个例子中,我们没有将深度参数传递给 flat() 方法,因此深度默认为 1。flat() 方法将嵌套数组 [3,4,5] 的所有元素连接到新数组的元素。
请注意, flat() 方法会创建一个新数组并且不会更改原始数组:
console.log(numbers);
输出:
[ 1, 2, [ 3, 4, 5 ] ]
以下示例将具有两级深度的数组展平:
const numbers = [1, 2, [3, 4, 5, [6, 7]]];
const flatNumbers = numbers.flat(2);
console.log(flatNumbers);
输出:
[1, 2, 3, 4, 5, 6, 7]
当我们不知道深度级别时,可以将 Infinity 传递给 flat() 方法,以递归方式将子数组的所有元素连接到新数组中:
const numbers = [1, 2, [3, 4, 5, [6, 7, [8, 9]]]];
const flatNumbers = numbers.flat(Infinity);
console.log(flatNumbers);
如果一个数组有空槽,我们可以使用 flat() 方法去除空洞,像这样:
const numbers = [1, 2, , 4, , 5];
const sequence = numbers.flat();
console.log(sequence);
输出:
[ 1, 2, 4, 5 ]