//数组扁平化
let testArray = [1, [2, [3, [4, [5]]]]];
Array.prototype.customFlat = function () {
let complate = []
for (let item of this) {
if (Array.isArray(item)) {
complate = complate.concat(item.customFlat());
}
else {
complate.push(item)
}
}
return complate
}
console.log('complate', testArray.customFlat());
console.log('flat', testArray.flat(Infinity));
通过Array.isArray(item) 判断当前item是不是数组 是数组 进行递归调用customFlat 方法
注意要使用function而不是箭头函数 否则this 指向window
普通函数谁调用指向谁 所以指向的是testArray