js 循环处理

图片描述

如果一数组里面的结构是这样的,怎么样才可以把里面多个数组的每个都取出来,形成单个索引只有1个数组,

阅读 1.7k
3 个回答
function loopItem(array, items) {
    array.forEach((item) => {
        if (Array.isArray(item)) {
            loopItem(item, items);
        } else {
            items.push(item);
        }
    });
    return items;
}

var array = [
    1,
    2,
    3,
    [4, 5],
    6,
    7,
    8,
    [9, 19]
];
var items = loopItem(array, []);

上面的是个例子,你可以直接红上面的loopItem方法

console.log(arr.reduce((a,b)=>{
    return a.concat(b)
},[]))

Array.prototype.concat.apply([],arr)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题