1.数组flat
const newArr = [1, 2, 3, [4, 5, [8, [9]]], [6, 7, [0]]];
// 手撸flat
/**
* prop:Number处理的层级
*/
Array.prototype.myFlat = function (prop = 1) {
if (typeof (prop) !== 'number') {
throw new TypeError('prop need Number');
}
const that = this;
if (!Array.isArray(that)) {
throw new TypeError('Data type is not Array');
}
let target = [];
// 当输入数据为无穷大时
if (prop === Infinity) {
target = that;
do{
target = target.myFlat(1);
}while(target.some(d=>Array.isArray(d)));
return target
}
if (prop <= 0) return that;
// 优化执行次数,当已经全部扁平 就不再走下面的逻辑
if (that.every(i => !Array.isArray(i))) return that;
prop--;
that.forEach(item => {
if (Array.isArray(item) && item.some(t => Array.isArray(t))) {
target = target.concat(item.myFlat(prop));
} else if (Array.isArray(item)) {
target = target.concat(item.myFlat(1))
} else {
target.push(item)
}
})
return target
}
console.log(newArr.myFlat(8));
2.