0

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 :

Uncaught TypeError: Cannot read property 'id' of undefined

Whereas I had add condition if the variable not exist

How can I solve it?

user94559
  • 59,196
  • 6
  • 103
  • 103
moses toh
  • 12,344
  • 71
  • 243
  • 443
  • Use `i < team.length`. You are traversing outside the size of the array. – Terry Jun 17 '17 at 04:48
  • Possible duplicate of [How do I check if an object has a property in JavaScript?](https://stackoverflow.com/questions/135448/how-do-i-check-if-an-object-has-a-property-in-javascript) – OmG Jun 17 '17 at 04:53
  • @OmG, Seems my case is different – moses toh Jun 17 '17 at 04:56
  • @Terry, If my code above run, I want the result on the console like this : `1 2 3 4 5`. If I use your answer, the result like this : `1 3 5 4 5` – moses toh Jun 17 '17 at 04:59
  • If you insist on running outside the size of the array, then check within the loop if `team[i]` is falsey first—it has to be the first check in your if conditional. – Terry Jun 17 '17 at 05:00
  • @TrendingNews Can you explain in English what you're trying to do? Why do you want the output 1 2 3 4 5? Where do those numbers come from? – user94559 Jun 17 '17 at 05:09

3 Answers3

1

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"}];

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

Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28
0

Few observations,

  1. Instead of hardcoded value '5' inside for loop you should use array length i.e. in this case team.length
  2. Instead of logging 'i+1' you can log 'i' as array index starts from '0'. Or simply you can print object/team name.

here is modified code,

<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>
Raj
  • 505
  • 1
  • 6
  • 14
  • I know it. But In my case it should use `for(var i = 0; i < 5; i++)` – moses toh Jun 17 '17 at 05:07
  • You can not use this. As your team array size is 3. While inside for loop you are trying to access 4th and 5th. Hence you get the type array as there is no 4th element in team array. – Raj Jun 17 '17 at 05:11
0

The main problem is that you are checking a property of an object, in this case team[i], that might be undefined.

For example, if you console.log(team[4]), which will point to undefined because there is only 3 objects in team. Checking a property of undefined will result in an error.

var arr = [1,2,3]

// this will be undefined
var element = arr[4]

console.log(element.toString)

So, you should also is check if team[i] is NOT undefined. Your code should look something like the code below. I am assuming that you want to print 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);
    }
}
Mμ.
  • 8,382
  • 3
  • 26
  • 36
  • This prints `1 3 5 4 5`, which has already been explicitly described as an incorrect output. (I don't know why, but it still seems silly to suggest an answer that gives this output.) – user94559 Jun 17 '17 at 05:12
  • Your new code is bizarre. Can you explain what led you to believe this would help the original poster? – user94559 Jun 17 '17 at 05:23
  • It is bizzare, but I am doing it for the sake of answering the question. – Mμ. Jun 17 '17 at 05:27
  • My assumption is that he wants to print 1 2 3 4 5 using his code, which i have slightly modified. – Mμ. Jun 17 '17 at 05:30
  • I assume that when he says 'How can I solve it?', he wants people to modify his code so that it prints 1 2 3 4 5, for whatever reason. – Mμ. Jun 17 '17 at 05:33
  • I'll let OP be the judge of that. – Mμ. Jun 17 '17 at 05:36