gpt4 book ai didi

javascript - 如何检查 JavaScript 中对象数组中的索引是否存在?

转载 作者:行者123 更新时间:2023-12-03 04:05:02 24 4
gpt4 key购买 nike

我的 JavaScript 代码是这样的:

<script type="text/javascript">
var team = [{id:"1", name:"chelsea"}, {id:"3", name:"mu"}, {id:"5", name:"arsenal"}];
for(var i = 0; i < 5; i++) {
if(team[i].id || typeof team[i].id !== 'undefined' || team[i].id !== null) {
console.log(team[i].id)
}
else {
console.log(i+1)
}
}
</script>

如果代码运行,控制台上会出现如下错误:

Uncaught TypeError: Cannot read property 'id' of undefined

如果变量不存在,我就添加条件

如何解决?

最佳答案

据我所知,当您在评论输出之一 1,2,3,4,5 中说您需要缺少的 id 时 - 在您的情况下有 2,4

var team = [{id:"1", name:"chelsea"}, {id:"3", name:"mu"}, {id:"5", name:"arsenal"}];
var empty_ids = 0;
for(var i = 0; i < 5; i++) {
if(team[i] && typeof team[i] !== 'undefined' && team[i] !== null) {
if(parseInt(team[i].id) !== i + 1){ // check if id on the array not equal the i + 1 from the loop
for( var k= 1 ; k < parseInt(team[i].id) - empty_ids ; k++){
console.log(empty_ids + k +" missing");
}
console.log(team[i].id);
}else{
console.log(team[i].id);
}
empty_ids = parseInt(team[i].id);
}else{
if(empty_ids <= i){
console.log(empty_ids + 1 + " undefined team[i]");
empty_ids = empty_ids + 1;
}

}
}

注意:即使您更改团队数组,此代码也将起作用

var team = [{id:"1", name:"chelsea"}, {id:"5", name:"arsenal"}]; 
//or
var team = [{id:"1", name:"chelsea"}, {id:"3", name:"mu"}, {id:"4", name:"arsenal"}];
//or
var team = [{id:"1", name:"chelsea"}, {id:"4", name:"arsenal"}];

因此,请尝试使用建议值更改 var team = ..我添加了 missingundefined 让您注意到console.log 来了

关于javascript - 如何检查 JavaScript 中对象数组中的索引是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44600855/

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