函数特点
const ary = [1,2,3,,5]
ary.flat()
函数用法
Array.prototype.flat(depth);
使用场景
const ary = [1,2,[3,4]]
ary.flat()
const ary2 = [1, [2], [3, [4]]]
ary2.flat(1)
const ary3 = [1,[2,[3,[4]]]]
ary3.flat(Infinity)
手写实现
const ary = [1,[2], [3, [4, 5, [6]]], [7], 8, 9];
function myFlat(list) {
let result = [];
list.forEach((item) => {
if (Array.isArray(item)) {
result = result.concat(arguments.callee(item));
} else {
result.push(item);
}
});
return result;
}
myFlat(ary);
const ary = [1,[2], [3, [4, 5, [6]]], [7], 8, 9];
Array.prototype.myFlat = function(num) {
if (!Number(num) || Number(num) < 0) return this;
let result = this.concat();
while (num > 0) {
if (result.some((v) => Array.isArray(v))) {
result = [].concat.apply([], result);
} else {
break;
}
num--;
}
return result;
}
ary.myFlat(Infinity);
ary.myFlat(2);
const ary = [1,[2], [3, [4, 5, [6]]], [7], 8, 9];
function myFlat(list) {
const stack = [].concat(list);
const result = [];
while(stack.length) {
const next = stack.pop();
if (Array.isArray(next)) {
stack.push(...next);
} else {
result.push(next);
}
}
return result.reverse();
}
myFlat(ary);