我在创建引用数组中对象内的数组的循环时遇到问题。
var data_dictionary = [{
"category": "Food",
"items": [
{
"object": "Apple",
"price": 2.21
},
{
"object": "Banana",
"price": 1.12
}
]
}, {
"category": "Goods",
"items": [
{
"object": "Lawnmower",
"price": 25.55
},
{
"object": "Bicycle",
"price": 12.21
}
]
}
]
我想运行一个循环来返回“对象”的数量,但我遇到了问题
var result =[]
var temp = []
for (var i=0; i < data_dictionary.length; i++) {
for (var c=0; c < data_dictionary[i].items.length; c++) {
temp.push (data_dictionary[i].items[c].object)
}
}
result.push (temp.length)
该问题与计算“c < data_dictionary[i].items.length”中的长度有关,也可能与下一行中的长度有关。
理想情况下,我希望结果为 4,因为有 4 个对象。
感谢您的阅读。
最佳答案
您的数据和代码应该是
var data_dictionary = [{
"category": "Food",
"items": [
{
"object": "Apple",
"price": 2.21
},
{
"object": "Banana",
"price": 1.12
}
]
}, {
"category": "Goods",
"items": [
{
"object": "Lawnmower",
"price": 25.55
},
{
"object": "Bicycle",
"price": 12.21
}
]
}
]
var result;
var temp = [];
for (var i=0; i < data_dictionary.length; i++) {
for (var c=0; c < data_dictionary[i].items.length; c++) {
temp.push (data_dictionary[i].items[c].object)
}
}
result = temp.length
关于javascript - 计算数组中对象内的数组长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37432665/