我的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>
如果代码运行,则在控制台上存在如下错误:
未捕获的TypeError:无法读取属性&#39; id&#39;未定义的
如果变量不存在我添加了条件
我该如何解决?
答案 0 :(得分:1)
据我所知,当你在评论输出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;
}
}
}
&#13;
注意:即使您更改了团队数组
,此代码仍然有效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 =
。我添加了missing
和undefined
,以便您注意console.log
来自哪里
答案 1 :(得分:0)
很少有观察,
这里是修改后的代码,
<script type="text/javascript">
var team = [{id:"1", name:"chelsea"}, {id:"3", name:"mu"}, {id:"5", name:"arsenal"}];
for(var i = 0; i < team.length; i++) {
if(team[i].id || typeof team[i].id !== 'undefined' || team[i].id !== null) {
console.log(team[i].id)
}
else {
console.log('team id not found for index ' + i);
}
}
</script>
答案 2 :(得分:0)
主要问题是你正在检查一个对象的属性,在本例中是team [i],可能是未定义的。
例如,如果你是console.log(团队[4]),它将指向未定义,因为团队中只有3个对象。检查未定义的属性将导致错误。
var arr = [1,2,3]
// this will be undefined
var element = arr[4]
console.log(element.toString)
&#13;
所以,您还应检查team [i]是否未定义。您的代码应该类似于下面的代码。我假设您要打印1,2,3,4,5。
var team = [{id:"1", name:"chelsea"}, {id:"3", name:"mu"}, {id:"5", name:"arsenal"}];
for(var i = 0; i < 5; i++) {
// check if team[i] is not undefined using (team[i] !== undefined)
if((team[i] !== undefined) && ( team[i].id || typeof team[i].id !== 'undefined' || team[i].id !== null)) {
var currentId = team[i].id > i + 1 ? i + 1 : team[i].id;
console.log(currentId)
}
else {
console.log(i + 1);
}
}
&#13;