在不使用嵌套 for 循环的情况下迭代 JavaScript 数组
问题描述:
我一直在尝试在 JavaScript 中迭代多维数组,并打印数组中的每个元素.有没有办法在不使用嵌套 for 循环的情况下打印多维数组中的每个元素?
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?
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])
}
Array.isArray
需要一个用于旧浏览器的垫片.
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]"
}