我一直在尝试在JavaScript中迭代多维数组,并打印数组中的每个元素.有没有办法在不使用嵌套for循环的情况下在多维数组中打印每个元素?
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?
}
Run Code Online (Sandbox Code Playgroud)
小智 13
听起来问题是你可能有任意深度的嵌套.在这种情况下,使用递归函数.
function printArray(arr) {
for (var i = 0; i < arr.length; i++)
if (Array.isArray(arr[i]))
printArray(arr[i])
else
console.log(arr[i])
}
Run Code Online (Sandbox Code Playgroud)
在Array.isArray需要对旧版浏览器垫片.
if (!Array.isArray)
Array.isArray = function(o) {
return !!o && Object.prototype.toString.call(o) === "[object Array]"
}
Run Code Online (Sandbox Code Playgroud)
如果您不想使用嵌套循环,则可以展平数组或使用递归函数.就像是:
arr.forEach(function each(item) {
if (Array.isArray(item))
item.forEach(each);
else
console.log(item)
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10107 次 |
| 最近记录: |