Reputation: 15
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?
Upvotes: 0
Views: 91
Reputation: 324
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];
}
Upvotes: 1
Reputation: 14588
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);
Upvotes: 1
Reputation:
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));
Upvotes: 0
Reputation: 73241
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);
Upvotes: 1