0

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?

3
  • You're looking for the wonders of arrays. Commented Jul 29, 2016 at 22:07
  • okay trying it now, thanks Commented Jul 29, 2016 at 22:12
  • @Boaz: No; just use a number (and make it zero-based). Commented Jul 29, 2016 at 22:13

2 Answers 2

1
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)
Sign up to request clarification or add additional context in comments.

Comments

0

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>

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.