遍历JavaScript数组,而不使用嵌套的for循环 [英] Iterate over a JavaScript array without using nested for-loops

查看:558
本文介绍了遍历JavaScript数组,而不使用嵌套的for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图遍历一个JavaScript多维数组,数组中打印每个元素。有什么办法来打印多维数组中的每个元素,而无需使用嵌套的for循环?

http://jsfiddle.net/mKsDW/

 变种改编= [[1,5],[7,4]];
对于(ARR中我VAR){
    警报(ⅰ); //这显示为0,然后显示1,
    //而不是阵列中的打印每个元件
    //我怎样才能让它每个二维数组中打印每个元素代替,
    //没有使用嵌套for循环的阵列的每一维?
}


解决方案

听起来就像是问题是,你可以有任意深度的嵌套。在这种情况下,使用一个递归函数。

 函数printArray(ARR){
    对于(VAR I = 0; I< arr.length;我++)
        如果(Array.isArray(ARR [I]))
            printArray(ARR [I])
        其他
            的console.log(ARR [I])
}

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

 如果(!Array.isArray)
    Array.isArray =功能(O){
        返回!!的O&&安培; Object.prototype.toString.call(O)===[对象数组]
    }

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?

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?
}

解决方案

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.isArray will need a shim for older browsers.

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

这篇关于遍历JavaScript数组,而不使用嵌套的for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆