将深度嵌套的数组,扁平化
Array.prototype.flat = function (n = 1) {
let current = this;
let count = 0;
// 校验数组为空/ 扁平参数0
if (!current.length || n == 0) return current;
// 捕获数组元素错误 [1, x];
try {
// 循环扁平
while (count++ < n) {
// 判断上一轮扁平化后的数组元素,都非数组
if (!current.some(Array.isArray)) return current;
// 不断把拉平的结果赋值给current,更新后返还
current = current.reduce((prev, next) => prev.concat(next), []);
}
} catch(error) {
throw error;
}
// 返回结果
return current;
}
验证
let arr = [1, [1, [3, [4, [5]]]]];
arr.flat("tom");
//[1, [1, [3, [4, [5]]]]]
arr.flat();
//[1, [1, [3, [4, [5]]]]]
arr.flat(1);
//[1, 1, [3, [4, [5]]]]
arr.flat(Infinity);
//[1, 1, 3, 4, 5]