我一直試圖在JavaScript中遍歷多維數組,並打印數組中的每個元素。有沒有辦法打印多維數組中的每個元素而不使用嵌套的for-loops?迭代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?
}
對於數組,您應該使用常規for循環而不是'for ... in'。是的,有可能沒有嵌套循環,但有什麼意義?嵌套循環是最具可讀性的解決方案。其他解決方案只會抽象一個級別的迭代。 – 2013-04-06 18:21:42
@FabrícioMatté爲10 x 10 x 10 x 10 x 10陣列編寫嵌套for循環將非常繁瑣,因此我需要更簡潔的解決方案。 – 2013-04-06 18:23:00
哦,我明白了。以爲它只是關於二維數組。 – 2013-04-06 18:23:22