gpt4 book ai didi

javascript当null时跳转到下一条记录代码修改

转载 作者:行者123 更新时间:2023-11-30 15:34:10 25 4
gpt4 key购买 nike

我有一些代码运行良好,但我遇到了问题。

基本上,当它到达一个 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);

我该怎么做?

最佳答案

如果设置了 thsub,您只能推送一个值。

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, 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 }] },
thCount = [];

for (var l = 0, m = data.cars.length; l < m; l++) {
if (data.cars[l].thsub) {
thCount.push(0);
for (var i = 0, j = data.cars[l].thsub.length; i < j; i++) {
if (data.cars[l].thsub[i].stats) {
thCount[thCount.length - 1] += data.cars[l].thsub[i].stats.items;
}
}
}
}

console.log(thCount);

关于javascript当null时跳转到下一条记录代码修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41824415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com