Skip to content Skip to sidebar Skip to footer

Javascript Array Cloning

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;

Solution 1:

The problem is that while Array.prototype.slice() will create a separate copy of the original array, its items will still be references to the same object instances. So modifying an item in one array ends up modifying the corresponding item in the cloned array.

If your items are simple data objects (no functions), this workaround might do the trick for you:

// instead of "var player_array = playerList.slice();"var player_array = JSON.parse(JSON.stringify(playerList));

Post a Comment for "Javascript Array Cloning"