Iterate over a JavaScript array without using nested for-loops

前端 未结 2 2051
孤独总比滥情好
孤独总比滥情好 2020-12-14 13:57

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 a

2条回答
  •  抹茶落季
    2020-12-14 14:21

    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]"
        }
    

提交回复
热议问题