flat()
方法的语法为:
arr.flat(depth)
在这里, arr是一个数组。
flat()参数
flat()
方法采用:
- depth (可选)-整数,用于指定嵌套数组应展平的深度。其默认值为1 。
从flat()返回值
- 返回一个包含子数组元素的新数组。
注意事项 :
-
flat()
方法不会更改原始数组。 -
flat()
方法删除数组中的空插槽。
示例:使用flat()方法
const arr1 = [1, [2, 3, 4], 5];
const flattened1 = arr1.flat();
console.log(flattened1); // [ 1, 2, 3, 4, 5 ]
const arr2 = [1, 2, [3, 4, [5, 6]]];
const flattened2 = arr2.flat();
console.log(flattened2); // [1, 2, 3, 4, [5, 6]]
const flattened3 = arr2.flat(2);
console.log(flattened3); // [ 1, 2, 3, 4, 5, 6 ]
const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
const flattened4 = arr4.flat(Infinity);
console.log(flattened4); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
// flat() removes holes
const numArr = [1, , 3];
console.log(numArr.flat()); // [ 1, 3 ]
输出
[ 1, 2, 3, 4, 5 ]
[ 1, 2, 3, 4, [ 5, 6 ] ]
[ 1, 2, 3, 4, 5, 6 ]
[
1, 2, 3, 4, 5,
6, 7, 8, 9, 10
]
[ 1, 3 ]
如示例所示,我们可以使用Infinity
将数组递归展平到任何深度。
推荐读物: JavaScript Array flatMap()