在不使用库函数的情况下使用真实/伪造的值展平数组-JavaScript
我们需要编写一个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 ]
热门推荐
10 贺卡祝福语情侣搞笑简短
11 老同学十一祝福语简短
12 猪年给老师祝福语简短
13 新婚祝福语大全简短经典
14 侄儿生日祝福语简短独特
15 新年祝福语简短句子
16 简短有力的结婚祝福语
17 考试祝福语简短给对象
18 朋友弟弟生日祝福语简短