计算数组中的属性

时间:2013-03-27 19:59:50

标签: javascript iteration dynamic-arrays naming-conventions

我正在尝试计算动态生成的数组中的属性。数组程序在对象内创建,如下所示:

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.

这是我记录(程序)时的数组:

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

似乎它将所有程序放在数组中作为一个字符串...或者其他东西。我很乐意将它们编入索引并能够迭代它们。有什么建议?

2 个答案:

答案 0 :(得分:1)

programs = state.programs;
console.log(programs.length);
如果state引用state_list数组中的对象,

将正确返回数组的长度。

我的猜测是代码中的program不是数字,程序是作为对象属性而不是数组索引插入的。如果您实际在程序[]中添加内容,则只会增加长度。如果program是非数字字符串,则您将编辑数组的属性而不是索引,这些不会增加长度。

答案 1 :(得分: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”