手写源码-实现 flat 拍平数组
2021-07-12 本文已影响0人
胡小喵_
- forEach 循环实现
const animals = ["🐷", ["🐶", "🐂"], ["🐎", ["🐑", ["🐲"]], "🐛"]];
Array.prototype.myFlat = function (number = 1) {
const array = this;
const res = [];
const getFlatArray = (array, _number) => {
if (_number < 0) {
res.push(array);
return;
}
array.forEach((item) => {
if (Object.prototype.toString.call(item) == "[object Array]") {
getFlatArray(item, _number - 1);
} else {
res.push(item);
}
});
};
getFlatArray(array, number);
return res;
};
console.log(
animals.myFlat(Infinity)
);
// ['🐷', '🐶', '🐂', '🐎', '🐑', '🐲', '🐛']
- 通过 concat 实现拍平
通过 arguments.callee 实现递归(只能在严格模式下使用)
const animals = ["🐷", ["🐶", "🐂"], ["🐎", ["🐑", ["🐲"]], "🐛"]];
Array.prototype.myFlat = function () {
const array = this;
let res = [];
array.forEach((item) => {
if (Array.isArray(item)) {
res = res.concat(arguments.callee(item));
} else {
res = res.concat(item);
}
});
return res;
};
console.log(animals.myFlat());
- 通过 reduce 实现,并可通过参数控制拍平层数。
const animals = ["🐷", ["🐶", "🐂"], ["🐎", ["🐑", ["🐲", [1]]], "🐛"]];
Array.prototype.myFlat = function (num=1) {
const array = this;
return num > 0
? array.reduce((acc, cur) => Array.isArray(cur) ? acc.concat(cur.myFlat(num - 1)) : acc.concat(cur),[])
: array;
};
console.log(animals.myFlat());
- 通过 generator 实现。
const animals = ["🐷", ["🐶", "🐂"], ["🐎", ["🐑", ["🐲", [1]]], "🐛"]];
Array.prototype.myFlat = function* (num = 1) {
const array = this;
for (let item of array) {
if (num > 0 && Array.isArray(item)) {
yield* item.myFlat(num - 1);
} else {
yield item;
}
}
};