1

Why different objects plyers[o] and plyers[1] are assigned the same value? Although there should be a difference of 1

var player = {
    'money': 1,
    'increase' : 10
}

var players = [];


for (var i=0;i<2;i++){
    players[i] = player;
}
for (var i=0;i<3;i++){
    for (var j=0;j<players.length;j++){
        players[j]['money'] += (players[j]['increase']+j)
        console.log(players[0].money + ' ___0')
        console.log(players[1].money + ' ___1')
    }
}

console :

11 ___0 
11 ___1 
22 ___0 
22 ___1 
32 ___0 
32 ___1 
jgillich
  • 71,459
  • 6
  • 57
  • 85
  • You are assigning references not values, so any change to player[0] will effect player[1] as both refer to the same player object. You must copy your object or try to create your 'var player' in first for loop. That way in every iteration a new player instance will be created. – Cem Özer Apr 25 '14 at 07:09

1 Answers1

2

When you do

players[i] = player;

you are not creating a copy of player and assign it to players[i], but making players[i] refer to player object. So, all the elements of the array are pointing to the same object.

What you might want to do is to clone the objects, like this

players[i] = JSON.parse(JSON.stringify(player));

Note: The cloning method I mentioned will work properly only when there are no functions in the objects and no inheritance chain. You can follow this question to know more about other ways to clone a JavaScript object.

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • 1
    @sankrish—there are many issues with copying objects. You need to be aware of exactly what you want to do with a copy, e.g. do you want to copy object properties too or just reference them? What should be done with DOM objects? Or other host objects? Dates? Functions? – RobG Apr 25 '14 at 09:41