循环遍历多维数组以迭代javascript中的每个项目

我怎样才能循环遍历每个项目console.log, 我只想迭代循环方式 这是数组


let array = [

    [1,2,3],

    [4,5,6],

    [7,8,9],

    [[10,11,12],13,14],

    [[15,16,16],[17,18,[19,20]]]

];


慕尼黑5688855
浏览 116回答 3
3回答

LEATH

获取一个平面数组并迭代输出。let array = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [[10, 11, 12], 13, 14], [[15, 16, 16], [17, 18, [19, 20]]]];array    .flat(Infinity)    .forEach(v => console.log(v));带有递归回调的更经典的方法。const show = v => {        if (Array.isArray(v)) v.forEach(show);        else console.log(v);    };let array = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [[10, 11, 12], 13, 14], [[15, 16, 16], [17, 18, [19, 20]]]];array.forEach(show);

森林海

你可以试试这样的东西吗?此函数应控制台记录数组和所有子数组中的每个项目。// using Array.forEachconst recursiveLoop1 = (elem) => {&nbsp; if (Array.isArray(elem)) {&nbsp; &nbsp; elem.forEach((innerElem) => {&nbsp; &nbsp; &nbsp; recursiveLoop1(innerElem)&nbsp; &nbsp; })&nbsp; } else {&nbsp; &nbsp; console.log(elem)&nbsp; }}// using classic for-loopconst recursiveLoop2 = (elem) => {&nbsp; if (Array.isArray(elem)) {&nbsp; &nbsp; for (let i = 0; i < elem.length; i++) {&nbsp; &nbsp; &nbsp; recursiveLoop2(elem[i])&nbsp; &nbsp; }&nbsp; } else {&nbsp; &nbsp; console.log(elem)&nbsp; }}let array = [&nbsp; [1,2,3],&nbsp; [4,5,6],&nbsp; [7,8,9],&nbsp; [[10,11,12],13,14],&nbsp; [[15,16,16],[17,18,[19,20]]]];recursiveLoop1(array);recursiveLoop2(array);

鸿蒙传说

你需要一个嵌套循环。JavaScript 有不同的方法来做到这一点。以下是函数式编程的示例:array.forEach(function (outer) {&nbsp; &nbsp; outer.forEach(function (inner) {&nbsp; &nbsp; &nbsp; &nbsp; console.log(inner)&nbsp; &nbsp; })});由于您有一个深度嵌套的数组,您可能还想先将其展平。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript