0

Looking to create a set of objects to the size of an array. In a loop I want to define these objects like such:

var playersNames = ["name1", "name2", "name3"];

for(i=0; i < playersNames.length; i++){
    var player[i] = new player();
    player[i].name = playersNames[i];
}

But JavaScript doesn't like the var player[i].

Any way I can do this?

0

4 Answers 4

1

Create an array first, then push() to it:

var playersNames = ["name1", "name2", "name3"];
var player = [];
function Player() {
	
}

for(i=0; i < playersNames.length; i++){
   player.push(new Player());
   player[i].name = playersNames[i];
}
            
console.log(player);

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

Comments

1

Or you can do something like this easily-

var playersNames = [
		     "name1",
		     "name2",
		     "name3"
		   ];
var players = [];

for(i=0; i < playersNames.length; i++)
{
	players.push( playersNames[i] );
}

console.log(players);

1 Comment

Updated to players from player
1

You can pre-allocate the player array:

var playersNames = ["name1", "name2", "name3"];
var nnames = playersNames.length;

var player = new Array(nnames);

for(i = 0; i < nnames; i++){
    player[i] = new Player();
    player[i].name = playersNames[i];
}

1 Comment

if u like to give any answer, please verify that answer before posting. Otherwise, nobody will be helped from the answer and your answers will be put as an underrated answer.
0

Use map:

var players = playersNames.map(playerName => {
  var myPlayer = new player();
  myPlayer.name = playerName;
  return myPlayer;
});

This avoids having to predeclare your players array and laboriously push to it one by one. Essentially, map does that work for you.

If you redesign your constructor to take the name as a parameter, it's even more compact:

var players = playerNames.map(playerName => new player(playerName));

Comments

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.