如何检查JavaScript中对象数组中的索引是否存在? [英] How can I check index in object array exist or no in javascript?
问题描述
我的JavaScript代码如下:
My javascript code like this :
<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>
如果代码运行,则在控制台上存在如下错误:
If the code run, on the console exist error like this :
未捕获的TypeError:无法读取未定义的属性'id'
Uncaught TypeError: Cannot read property 'id' of undefined
如果变量不存在则具有添加条件
Whereas I had add condition if the variable not exist
我该如何解决?
推荐答案
据我了解,当您在评论输出 1,2,3,4,5
之一中说时,您需要缺少ID —在您的情况下是 2,4
As I understand when you said on one of your comment output 1,2,3,4,5
that you need the missing ids -- In your case there are 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;
}
}
}
注意:此即使更改团队数组,代码也将起作用
Note: this code will work even if you change the team array
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 =
与建议的值..我添加了缺少
和未定义
,以使您注意到的位置console.log
So please try to change var team =
with suggested values .. I added a missing
and undefined
to let you notice from where the console.log
comes
这篇关于如何检查JavaScript中对象数组中的索引是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!