I have this way to make an array
var playerList = [];
exports.player = function(socket, name)
{
this.id = socket.id;
this.name = name;
this.x = 20;
this.y = 40;
return this
}
exports.addPlayer = function(data)
{
playerList.push(data)
}
And I'm adding items to playerList array like this
var client = new player(socket, data);
exports.addPlayer(client);
But I also got a function that makes the following
exports.getSafeList = function(id)
{
var player_array = playerList.slice();
for(var i = 0; i < player_array.length; i++)
{
if(player_array[i].id != id)
{
player_array[i].id = 'unknown';
}
}
return player_array;
}
And now I do the following
exports.getPlayerList = function()
{
return playerList;
}
console.log(players.getPlayerList())
console.log(players.getSafeList(id))
So far the code is working fine but when I log the 2 functions it seems that getPlayerList variable merges with player_list one, this is the output
When theres just ONE player on the array
[ { id: 'tjvh8XdMtX-o6QYDAAAB', name: 'Raggaer', x: 20, y: 40 } ]
[ { id: 'tjvh8XdMtX-o6QYDAAAB', name: 'Raggaer', x: 20, y: 40 } ]
But when there are more:
[ { id: 'unknown', name: 'Raggaer', x: 20, y: 40 },
{ id: '2-K5At07wLV4BDiAAAAC', name: 'Alvaro', x: 20, y: 40 } ]
[ { id: 'unknown', name: 'Alvaro', x: 20, y: 40 },
{ id: '2-K5At07wLV4BDiAAAAC', name: 'Alvaro', x: 20, y: 40 } ]
As you can see on both arrays id appears as "unknown" when it shouldn't, since I'm not modyfing the playerList array...
playerList.slice()only creates a shallow copy. Both arrays will refer to the same objects.