按照一个可指定的深度递归遍历数组:
let nestedArray = [1, 2, [3, 4, [5, 6]]]; | |
let flatArray = nestedArray.flat(); | |
console.log(flatArray); | |
// 输出: [1, 2, 3, 4, [5, 6]] | |
// 指定深度为 2 | |
let deeplyNestedArray = [1, 2, [3, 4, [5, 6]]]; | |
let deeplyFlatArray = deeplyNestedArray.flat(2); | |
console.log(deeplyFlatArray); | |
// 输出: [1, 2, 3, 4, 5, 6] |
使用 Infinity,可展开任意深度的嵌套数组:
var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]; | |
arr4.flat(Infinity); | |
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |