我基本上只是試圖循環訪問一系列數組(動態創建)並在控制檯中輸出結果。調試器告訴我this.allitems[i]
未定義。如何遍歷allItems對象中的每個數組?通過對象中的多個數組進行計數和循環
var warehouse = {
allItems: {
shirts:[],
shorts:[]
},
// Counts how many arrays are in the object
countArraysInAllItems: function(obj){
var size = 0,key;
for(key in obj){
if(obj.hasOwnProperty(key)) size++;
}
return size;
},
// Display the items from the arrays (in no particular order)
displayItems: function(){
var allItemsLength = this.countArraysInAllItems(this.allItems);
for(var i=0; i<allItemsLength; i++){
var itemSubArray = this.allItems[i];
for(var j=0; j<itemSubArray.length; j++){
var itemType = this.itemSubArray[j].itemType;
var itemName = this.itemSubArray[j].itemName;
var itemQuantity = this.itemSubArray[j].itemQuantity;
console.log('Type:' + itemType + '\n' +
'Name: ' + itemName + '\n' +
'Qty:' + itemQuantity);
}
}
}
'allItems'是一個對象,而不是一個數組。所以你應該像'allItems.shirts [i]'一樣做。 – kaitoy