TopTomato
TopTomato

Reputation: 585

Using a loop counter how can I dynamically create objects and use the counter in naming the objects?

I’m trying to dynamically create objects, using a loop counter. And want to use the counter itself in the naming the objects. The end result would be an array of players like this:

players = [
    p1: {
        //some data like age, score etc.
    },
    p2: {
        //some data like age, score etc.
    },
    p3: {
        //some data like age, score etc.
    }
]

but my simple code below is not working.

var numPlayers = 3;
var p;

var player = {
    rollDice : function(){
        console.log('i am rolling the dice');
        },
    age: function(){
        console.log("My name is " + this.age);
       },
    score:0
  }

for(i=0;i<numPlayers;i++){
    var p + i = Object.create(player);
    console.log('player ' + p + i + " created!");
    }

the problem is this line:

var p + i = Object.create(player);

i've tried various ways to make it work like

var 'p' + i = Object.create(player);

how can this be achieved?

Upvotes: 0

Views: 297

Answers (2)

Sen Qiao
Sen Qiao

Reputation: 126

Edit: It seems I am not the only one to think of a dictionary, sorry for the duplicate References: Append values to javascript dictionary

How to create dictionary and add key value pairs dynamically in Javascript

I would recommend a dictionary since you can reference based on strings (like 'p1' ) rather than only with index that are int (like 0) Additionally, I am unfamiliar with "Object.create()" but I don't think it is necessary when player is already an object.

Here is what I have:

<!DOCTYPE html>
<html>

<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
    </style>
    <title>Something</title>
</head>
<body>

</body>

<script>

new player={}

var numPlayers = 3;
var oneplayer={
    rollDice : function(){
        console.log('i am rolling the dice');
        },
    age: function(){
        console.log("My name is " + this.age);
       },
    score:0
}
var count =1



function dictionary(numPlayers){
    tempkey='p'+count
    player.push({key: , value: oneplayer})
    count=count+1
}

</script>
</html>

Upvotes: 0

jonathanGB
jonathanGB

Reputation: 1540

var players = {}

for(var i=0; i<numPlayers; i++){
  players['p' + i] = Object.create(player);
  console.log('player ' + ('p' + i) + " created!");
}

// var p; <-- not necessary

Now you have an associative array of players. If you do this, you'll see all the keys of this list:

Object.keys(players)

Upvotes: 1

Related Questions