我尝试使用 if 语句循环,其中 if 语句应跳过 null 值。但有些它不会识别空值。
我的数组对象值有这个
[ { "id": 17, "match_id": 17, "dktournament_id": 10, "seed_match": 1, "created_at": "2020-02-11 21:37:47", "updated_at": "2020-02-11 21:37:53", "score": { "id": 17, "playerOne": "Knud", "playerTwo": "Weise", "setOne": 3, "setTwo": 0, "created_at": "2020-02-11 21:37:53", "updated_at": "2020-02-11 21:38:21" } }, { "id": 18, "match_id": 18, "dktournament_id": 10, "seed_match": 2, "created_at": "2020-02-11 21:37:47", "updated_at": "2020-02-11 21:39:07", "score": { "id": 18, "playerOne": "Hans", "playerTwo": "Khan", "setOne": 0, "setTwo": 3, "created_at": "2020-02-11 21:39:07", "updated_at": "2020-02-11 21:39:42" } }, { "id": 19, "match_id": 19, "dktournament_id": 10, "seed_match": 3, "created_at": "2020-02-11 21:37:47", "updated_at": "2020-02-11 21:44:12", "score": { "id": 19, "playerOne": "Preben", "playerTwo": "Gertrud", "setOne": 1, "setTwo": 0, "created_at": "2020-02-11 21:44:12", "updated_at": "2020-02-21 12:24:39" } }, { "id": 20, "match_id": 20, "dktournament_id": 10, "seed_match": 4, "created_at": "2020-02-11 21:37:47", "updated_at": "2020-02-11 21:58:02", "score": { "id": 20, "playerOne": "Ingvard", "playerTwo": "Oscar", "setOne": 0, "setTwo": 0, "created_at": "2020-02-11 21:58:02", "updated_at": "2020-02-11 21:58:02" } }, { "id": 21, "match_id": null, "dktournament_id": 10, "seed_match": 5, "created_at": "2020-02-11 21:37:47", "updated_at": "2020-02-11 21:37:47", "score": null }, { "id": 22, "match_id": null, "dktournament_id": 10, "seed_match": 6, "created_at": "2020-02-11 21:37:47", "updated_at": "2020-02-11 21:37:47", "score": null }, { "id": 23, "match_id": null, "dktournament_id": 10, "seed_match": 7, "created_at": "2020-02-11 21:37:47", "updated_at": "2020-02-11 21:37:47", "score": null }, { "id": 24, "match_id": null, "dktournament_id": 10, "seed_match": 8, "created_at": "2020-02-11 21:37:47", "updated_at": "2020-02-11 21:37:47", "score": null } ]
我的方法是这样的
totalsetsTeamOne(){
let i;
let SetOneTotal = 0;
for (i = 0; i < 8; i++) {
if(this.seedmatches[i]!= null){
SetOneTotal += this.seedmatches[i].score.setOne;
}
}
this.setOneTotal = SetOneTotal;
console.log(SetOneTotal)
},
我的错误是这样的
[Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'setOne' of null"
最佳答案
你的 if 语句应该是
if(this.seedmatches[i] && this.seedmatches[i].score){
SetOneTotal += this.seedmatches[i].score.setOne;
}
因为你只是检查 this.seedmatches[i] 中是否有值。但是如果 this.seedmatches[i] 中有值但 this.seedmatches[i].score 为空怎么办?因此,我们需要彻底检查 this.seedmatches[i].score 是否也为 null。
关于javascript - 对象值循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60339995/