0

I have an array which I want to use to store properties in.

For example:

player[0].name = bla1;
player[0].money = 130;

Now I created the for loop, but when I try to store the name in it, I get an error.

   var player = [];
   for(i=0; i < players; i++)
   {
     var x = i + 1;
     var nickName = document.getElementById('player' + x + 'name').value
     player[i].name = nickName;
     console.log(player[i].name);
   }

I got the error when I tried to add the property:

 player[i].name = nickName;
 console.log(player[i].name)
1
  • What is the error ? Commented Mar 22, 2017 at 16:32

3 Answers 3

2

First there is no length, so I am not sure exactly what you are looping over

for(i=0; i < players; i++)  <--

And if the index is undefined, you would need to add an object into the empty index.

player[i] = player[i] || {};  //If there is no player defined, add an object
player[i].name = nickName;
Sign up to request clarification or add additional context in comments.

3 Comments

@T.J.Crowder So did I until I looked at it again and did the Ninja edit. lol
Oh sorry, it's from another piece of code, should I leave it like this or should I edit it in? Thanks for explanation about players[i] || {}; btw ;)
@C.Ronaldo It should be i < players.length if that is what you are asking. Personally I would use forEach()
1

You need to create the object before you can put properties on it:

var player = [];
for(i=0; i < players; i++)
{
    var x = i + 1;
    var nickName = document.getElementById('player' + x + 'name').value
    player[i] = {};                   // *** Create the object
    player[i].name = nickName;
    console.log(player[i].name);
}

And while you're at it, you can add the property while creating:

var player = [];
for(i=0; i < players; i++)
{
    var x = i + 1;
    var nickName = document.getElementById('player' + x + 'name').value
    player[i] = {
        name: nickName
    };
    console.log(player[i].name);
}

2 Comments

Thanks for the explanation! Gonna accept this answer in 10 minutes (after the timer). Kinda trying to figure out how objects work, thanks a lot!
@C.Ronaldo: Note epascarello's thing about length, which I have to admit I read right past in the code above.
1

You should set player[i] as an object first. So it will be :

 var player = [];
 for(i=0; i < players; i++)
 {
   var x = i + 1;

   var nickName = document.getElementById('player' + x + 'name').value
   player[i] = player[i] || {};
   player[i].name = nickName;
   console.log(player[i].name);
 }

2 Comments

Thanks for your reply, could you explain what players[i] || {} does? Never seen it before.
JavaScript || operator is logical OR. So it will return first passed value which is true. It means if players[i] exist use it if not declare new object;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.