在这里插入代码片
let arr = [1, 2, 3, 4, 5, 6, [1, 2, [3, 4, 5, [6, 7, 8]], 1, 2, [1, 2, 3, [3, 4, 5]]], 12, 3, 4, 5, [1, 2, 3], 1]
Array.prototype._flat = function (layer) {
let res = [];
if (layer <= 0) return this;
this.forEach((item) => {
if (Array.isArray(item)) {
res = res.concat(item._flat(layer - 1))
} else {
res.push(item);
}
})
return res;
}
console.log(arr._flat(2));
手写Array.flat()函数
最新推荐文章于 2022-10-25 15:36:49 发布