不使用嵌套的for循环来迭代JavaScript数组

4
我一直在尝试在JavaScript中迭代多维数组,并打印数组中的每个元素。有没有不使用嵌套for循环打印多维数组中每个元素的方法? 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?
}

对于数组,应该使用常规的for循环而不是for...in。是的,可以做到没有嵌套循环,但意义何在? 嵌套循环是最可读且全面的解决方案。其他解决方案只是抽象了一层迭代。 - Fabrício Matté
@FabrícioMatté,如果要编写10 x 10 x 10 x 10 x 10数组的嵌套for循环将非常繁琐,因此我需要更简洁的解决方案。 - Anderson Green
哦,我明白了。我以为这只涉及到二维数组。 - Fabrício Matté
2个回答

16

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

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

Array.isArray 在旧版浏览器中需要一个 shim。

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

不错的 shim,不过我想知道真值检查(!!o)是仅仅为了安全起见/优化还是实际上是必要的? - Fabrício Matté
@FabrícioMatté:是的,这并不是真正需要的。toString 部分通常是最慢的,所以如果我真的想避免它,我会这样做 !!o && typeof o === "object" && ... - user1106925
1
我通常使用MDN的shim,但这个看起来也不错(因为它基本上是相同的) - adeneo

6

如果您不想使用嵌套循环,可以将数组展平或使用递归函数。类似这样:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接