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?

6
  • Use i < team.length. You are traversing outside the size of the array. Commented Jun 17, 2017 at 4:48
  • Possible duplicate of How do I check if an object has a property in JavaScript? Commented Jun 17, 2017 at 4:53
  • @OmG, Seems my case is different Commented Jun 17, 2017 at 4: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 Commented Jun 17, 2017 at 4: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. Commented Jun 17, 2017 at 5:00

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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>

2 Comments

I know it. But In my case it should use for(var i = 0; i < 5; i++)
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.
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);
    }
}

6 Comments

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.)
Your new code is bizarre. Can you explain what led you to believe this would help the original poster?
It is bizzare, but I am doing it for the sake of answering the question.
My assumption is that he wants to print 1 2 3 4 5 using his code, which i have slightly modified.
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.