2013-03-27 57 views
0

我想在動態生成的數組中計數屬性。該陣列程序是對象內創建如下:在一個數組中計數屬性

state_list.push({name: state, undergrad: 0, grad: 0, total: 0, programs: []}); 

,然後後者被填充這樣的:

n = findWithAttr(state_list, 'name', state); 
//n = the index of property "name" with value of "state" in state_list 
if(!(program in state_list[n]["programs"])) {   
state_list[n]["programs"][program] = 1; 
} else { 
state_list[n]["programs"][program]++; 
} 

接下來,我需要總量可達的已放置在節目的數量陣列,並曾希望做到這一點的:

programs = state.programs; 
console.log(programs.length); 

但這回0

她e是數組,如果我登錄(程序):

Array[0] 
History, MA: 3 
Info Assurance & Security, MS: 1 
International Literacy, MED: 1 
length: 0 
__proto__: Array[0] 
main.js:237 

現在看來似乎是把所有的項目在陣列中作爲一個字符串...什麼的。我很樂意讓他們索引,並有能力遍歷它們。有什麼建議麼?

+0

if語句中的」程序「是什麼? – 2013-03-27 20:10:02

+0

公共管理MPA < - 這是用「program = data [i] [」Academic Program「]創建的程序的日誌輸出示例。」 – Jeremythuff 2013-03-27 20:51:45

+0

您是否能夠在此解決您的問題? – 2013-04-01 16:14:31

回答

0

好了,這是我落得這樣做:

programs = state.programs; 
keys = Object.keys(programs); 
//this creates an indexed array of each property in programs 
size = keys.length; 
//this gives me the length of the new array, which I can use for pagination 

然後我就能夠在它們之間迭代,像這樣:

offset = 0; 
results = 24; 
start = 0;    
$(keys).each(function() { 
    if((start >= offset)&&(start < (offset+results))) { 
    //this conditional gives me the pagination 
     $("#programResult").append("<li>"+this+": "+programs[this]+"</li>"); 
    } 
    start++; 
}); 

,給了我一個結果,其內容,如:「歷史, MA:1「

1
programs = state.programs; 
console.log(programs.length); 

如果狀態指向state_list數組中的對象,將正確返回數組的長度。

我的猜測是你的代碼中的program不是一個數字,程序被插入爲對象屬性而不是數組索引。如果你真的在程序[]中添加東西,長度只會增加。如果program是非數字字符串,那麼您將編輯數組的屬性而不是索引,並且這些不會增加長度。