2013-03-27 41 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是非数字字符串,那么您将编辑数组的属性而不是索引,并且这些不会增加长度。

相关问题