[英]Iterate over a JavaScript array without using nested for-loops
I've been trying to iterate over a multidimensional array in JavaScript, and print each element in the array. 我一直在尝试在JavaScript中迭代多维数组,并打印数组中的每个元素。 Is there any way to print each element in a multidimensional array without using nested for-loops?
有没有办法在不使用嵌套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?
}
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. Array.isArray
将需要旧版浏览器的垫片。
if (!Array.isArray)
Array.isArray = function(o) {
return !!o && Object.prototype.toString.call(o) === "[object Array]"
}
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)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.