在不使用库函数的情况下使用真实/伪造的值展平数组-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 教师闺蜜祝福语简短