seanbulley seanbulley - 4 months ago 15
Javascript Question

Variable Object Declaration Name in JavaScript

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?

mmm mmm
Answer

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); // [Player, Player, Player]

fiddle Demo

Comments