在不使用嵌套 for 循环的情况下迭代 JavaScript 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15854425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:19:57  来源:igfitidea点击:

Iterate over a JavaScript array without using nested for-loops

javascriptarrays

提问by Anderson Green

I've been trying to iterate over a multidimensional array in JavaScript, and print each element in the array. Is there any way to print each element in a multidimensional array without using nested for-loops?

我一直在尝试在 JavaScript 中迭代一个多维数组,并打印数组中的每个元素。有没有办法在不使用嵌套 for 循环的情况下打印多维数组中的每个元素?

http://jsfiddle.net/mKsDW/

http://jsfiddle.net/mKsDW/

var arr = [[1, 5],[7, 4]];
for(var i in arr){
    alert(i); //this displays "0", then displays "1",
    //instead of printing each element in the array
    //how can I make it print each element in each 2D array instead,
    //without using nested for-loops for each dimension of the array?
}

回答by

Sounds like the issue is that you may have a nesting of arbitrary depth. In that case, use a recursive function.

听起来问题在于您可能有任意深度的嵌套。在这种情况下,请使用递归函数。

function printArray(arr) {
    for (var i = 0; i < arr.length; i++)
        if (Array.isArray(arr[i]))
            printArray(arr[i])
        else
            console.log(arr[i])
}

The Array.isArraywill need a shim for older browsers.

Array.isArray需要对旧版浏览器垫片。

if (!Array.isArray)
    Array.isArray = function(o) {
        return !!o && Object.prototype.toString.call(o) === "[object Array]"
    }

回答by ZER0

If you don't want to use nested loops, you can either flat the array or use a recursive function. Something like:

如果您不想使用嵌套循环,您可以将数组平展或使用递归函数。就像是:

arr.forEach(function each(item) {
  if (Array.isArray(item))
    item.forEach(each);
  else
    console.log(item)
});