【发布时间】:2026-01-31 03:55:02
【问题描述】:
我有一些运行良好的代码,但我遇到了问题。
基本上,当它到达一个为 NULL 的记录时,它会在数组中添加一个 0...
在这种情况下,第二条记录为 NULL,所以我得到:
[10, 0, 20]
我需要它做的是,如果 thsub 为 NULL,则不向数组中添加任何内容并继续下一条记录。
所以在这种情况下,期望的结果是:
[10, 20]
这是完整的代码:
var data = {
"cars": [{
"id": "1",
"name": "name 1",
"thsub": [{
"id": "11",
"name": "sub 1",
"stats": {
"items": 5,
},
"ions": null
}, {
"id": "22",
"name": "sub 2",
"stats": {
"items": 5,
},
"translations": null
}],
"image": null
},
{
"id": "2",
"name": "name 2",
"thsub": null, //this will break the code
"image": null
},
{
"id": "54",
"name": "name something",
"thsub": [{
"id": "65",
"name": "sub 1",
"stats": {
"items": 10,
},
"ions": null
}, {
"id": "22",
"name": "sub 2",
"stats": {
"items": 10,
},
"translations": null
}],
"image": null
}
]
}
var thCount = [];
for (var l = 0, m = data.cars.length; l < m; l++) {
thCount[l] = 0;
if (data.cars[l].thsub) {
for (var i = 0, j = data.cars[l].thsub.length; i < j; i++) {
if (data.cars[l].thsub[i].stats) {
thCount[l]+=data.cars[l].thsub[i].stats.items;
}
}
}
}
console.log(thCount);
我该怎么做?
【问题讨论】:
标签: javascript arrays data-structures iteration reduce