简单回顾一下
var newArray = arr.flat([depth])
参数 depth 可选 指定要提取嵌套数组的结构深度,默认值为 1。
返回值 一个包含将数组与子数组中所有元素的新数组。
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());
// expected output: [0, 1, 2, 3, 4]
const arr2 = [0, 1, 2, [[[3, 4]]]];
console.log(arr2.flat(2));
// expected output: [0, 1, 2, [3, 4]]
es5实现
便于大家理解,直接就用最简单的for循环+if判断+递归调用
可能有些朋友对于js递归调用不太熟悉,我在js专栏开一篇文章为大家讲解一下
const arr = [1, 2, 3, [
[
[4, 5, [6, 7]]
]
]];
const _flat = function(arr, depth) {
let result = [];
depth--;
for (let i = 0; i < arr.length; i++) {
if (arr[i] instanceof Array && depth >= 0) {
for (let j = 0; j < _flat(arr[i], depth).length; j++) {
result.push(_flat(arr[i], depth)[j]);
}
} else {
result.push(arr[i]);
}
}
return result;
};
const newArr = _flat(arr, 1);
console.log(newArr);
const newArr2 = _flat(arr, 2);
console.log(newArr2);
const newArr3 = _flat(arr, 3);
console.log(newArr3);
const newArr4 = _flat(arr, 4)
console.log(newArr4);
不知道大家get到没有,深度决定遍历数组维度的次数深度越大,就越能遍历出高维度的数组
项并将值作为最外层数组的子项。