我们需要编写一个JavaScript数组函数,该函数接受具有伪造值的嵌套数组,并返回一个数组,其中包含数组中存在的所有元素而没有任何嵌套。
例如-如果输入为-
const arr = [[1, 2, 3], [4, 5, [5, false, 6, [5, 8, null]]], [6]];
那么输出应该是-
const output = [1, 2, 3, 4, 5, false, 6, 5, 8, null, 6];
以下是代码-
const arr = [[1, 2, 3], [4, 5, [5, false, 6, [5, 8, null]]], [6]];
const flatten = function(){
let res = [];
for(let i = 0; i < this.length; i++){
if(Array.isArray(this[i])){
res.push(...this[i].flatten());
}else{
res.push(this[i]);
};
};
return res;
};
Array.prototype.flatten = flatten;
console.log(arr.flatten());输出结果
这将在控制台中产生以下输出-
[ 1, 2, 3, 4, 5, 5, false, 6, 5, 8, null, 6 ]