2012-04-04 84 views
2
陣列收集

我遇到麻煩迭代和數組的集合(數組的數組,我猜)迭代在Javascript

我希望下面的代碼會顯示一個警告的表現中得到的值依次在每個陣列的3個值(例如,「嬰兒」,「0」,然後選擇「2」),但該警報只是顯示爲「0」,「不確定」,不確定的」。

我缺少什麼?

聲明該陣列:

var ageGroups = [["infant", 0, 2], ["child", 3, 18], ["child", 3, 17], ["adult1", 18, 64], ["adult2", 65, 74], ["adult3", 75, 79]]; 

遍歷數組

for (var item in ageGroups) { 
    alert(item[0]); 
    alert(item[1]); 
    alert(item[2]); 
} 
+0

反正你需要知道什麼是對環回報項目作爲字符串,當前屬性的名稱環路仰視,不是一個對象或數組,所以在不是一個foreach你可以在其他語言中找到,在ES5中有一個forEach函數,雖然 – mpm 2012-04-04 13:07:51

回答

4

代替警報使用console.log的性能,警報將只顯示[對象],如果變量是一個對象但在控制檯你可以看到什麼樣的對象,你可以調試進一步

for (var item in ageGroups) { 
    console.log(ageGroups[item][0]); 
    console.log(ageGroups[item][1]); 
    console.log(ageGroups[item][2]); 
} 
+0

感謝Sandeep。從來沒有想過使用console.log – BrightonDev 2012-04-11 08:06:00

0

不要使用for in來遍歷數組中的JavaScript。其目的是遍歷對象屬性。代替使用一個增量for循環..

for (var i=0; i<ageGroups.length; i++) { 
    for (var j=0; j<ageGroups[i].length; j++) { 
    console.log(ageGroups[i][j]); 
    } 

    // Or instead of an inner loop access them individually 
    console.log(ageGroups[i][0]); 
    console.log(ageGroups[i][1]); 
    console.log(ageGroups[i][2]); 
} 

See it in action...

使用一個陣列上的for-in構建體可產生如果,例如,你喜歡myArr[3] = 123;只定義了一個數組項比增量環路大大不同的結果。在這種情況下,JavaScript將分配項目0-2,for循環會迭代它們,但for-in不會。更重要的是,外部腳本和框架可能會擴展Array原型,並添加屬性,當你真的想要數組元素時,它將突然包含在迭代器中。

0

你應該做

for (i = 0; i <ageGroups.length; i++) { 
    var item = ageGroups[i]; 
    alert(item[0]); 
    alert(item[1]); 
    alert(item[2]); 
} 

for..in在JavaScript中,用於遍歷對象

1
for (var item in ageGroups) { 
    alert(ageGroups[item][0]); 
    alert(ageGroups[item][1]); 
    alert(ageGroups[item][2]); 
} 
1

你porblem是產品的陣列的

關鍵試試這個:

for (var item in ageGroups) { 
    alert(ageGroups[item][0]); 
    alert(ageGroups[item][1]); 
    alert(ageGroups[item][2]); 
} 
0

這裏有一個優化的for循環,我存儲長度這裏,所以它不會在每次迭代計算:

for (var i = 0, l = ageGroups.length; i < l; i++){ 
    alert(ageGroups[i][0]); 
    alert(ageGroups[i][1]); 
    alert(ageGroups[i][2]);  
} 

,使其完全一樣的例子中,你可以存儲ageGroup的迭代中的變量:

for (var i = 0, l = ageGroups.length, item; i < l; i++){ 
    item = ageGroups[i]; 
    alert(item[0]); 
    alert(item[1]); 
    alert(item[2]); 
} 
1

使用該死的forEach! :-)雖然不是跨瀏覽器,但墊片很容易實現。

// Call forEach and define the callback function 
ageGroups.forEach(loopArray) 

// Now let's work with the array! 
function loopArray(ageGroup) { 
    console.log(ageGroup[0]) 
    console.log(ageGroup[1]) 
    console.log(ageGroup[2]) 
}