【发布时间】:2015-10-07 12:40:08
【问题描述】:
我在用 javascript 计算这个数组中的对象数量时遇到了麻烦。 下面是我尝试用我的代码计算的对象数组。
<script>
var arr = [
{"gateways":["ccu1"],"manufacturer":["homematic"],"ir":["ir_no"],"ip":["ip_cam","ip_other"]},
{"gateways":["v3"],"manufacturer":["homematic"],"ir":["ir_no"],"ip":["ip_cam"]},
{"gateways":["v2","v3","v4","ccu2"],"manufacturer":["homematic","intertechno"],"ir":["ir_yes"],"ip":["ip_cam","ip_other"]},
{"gateways":["v2","ccu1","ccu2"],"manufacturer":["homematic"],"ir":["ir_yes"],"ip":["ip_cam","ip_other"]},
{"gateways":["gw_none"],"manufacturer":["homematic"],"ir":["ir_no"],"ip":["ip_cam"]},
{"gateways":["v3","ccu2"],"manufacturer":["homematic","fs20","intertechno","elro","Eltako Enocean"],"ir":["ir_yes"],"ip":["ip_cam","ip_other"]},
{"gateways":["v3","v4"],"manufacturer":["homematic"],"ir":["ir_no"],"ip":["ip_other"]},
{"gateways":["v3","v4"],"manufacturer":["homematic"],"ir":["ir_no"],"ip":["ip_other"]},
{"gateways":["v2"],"manufacturer":["intertechno"],"ir":["ir_yes"],"ip":["ip_other"]}
];
var counter = [];
for(var i=0; i<arr.length; i++) {
//console.log(arr[i]);
for(var index in arr[i]) {
console.log(index);
if(counter[index] === undefined) {
counter[index] = [];
}
}
}
console.log(counter);
</script>
我希望在控制台记录“计数器”时将对象的数量推入空数组“计数器”,例如
网关
ccu2 42
v4 70
v2 95
v3 91
v4plus 32
ccu1 16
gw_none 10
IP
ip_cam 4
ip_other 10
ip_none 4
他们
ir_yes 13
ir_no 18
制造商
家庭式 24
fs20 59
国际技术 38
埃尔罗 63
家常 40
苏菲 11
我是编程新手,我尝试过一些类似这样的练习,但我被卡住了。我留下了将对象计数器放入空数组的代码。我试过但不能让它工作。我会很感激任何帮助,我希望我的任务是有意义的并且是可以理解的。
【问题讨论】:
-
数组中没有
arr.length对象吗? -
首先将
counter初始化为一个对象,而不是一个数组,即var counter = {};。数组使用数字键,而您想使用字符串作为键。 jsfiddle.net/frsbawwz
标签: javascript arrays json loops if-statement