我有一個for循環,它基本上遍歷了一個類別列表。每個類別(字符串)有4個不同的項目,可以是真或假。下面是我的代碼片段:在JS中創建對象
var i,
category,
items,
categories= {};
for (i = 0; i < categories.length; i++) {
category = categories[i];
items = {};
items.first = availableItems[i][0] == true;
items.second = availableItems[i][1] == true;
items.third = availableItems[i][2] == true;
items.fourth = availableItems[i][3] == true;
categories+= { category : items};
}
什麼,我想最終是一個類的物體,像下面的結構:
{ category1 : {
first : true,
second : true,
third : false,
fourth : true
},
category2 : {
first : true,
second : true,
third : false,
fourth : false
},
category3 : {
first : true,
second : true,
third : false,
fourth : false
}
}
誰能告訴我什麼,我做錯了什麼?
'類別+ = {category:items};'真的嗎?我建議使用'categories'作爲_array_,然後使用'push'來添加數組中的對象。 'var categories = [];''''''''''''''''''使用'categories.push({category:items});' – Tushar
@Tushar - 我是JS的新手,所以如果你能給我一個很棒的例子 – user1809790
@ user1809790在他的評論中有一個例子。 – Mathletics