Pablo Estrada Pablo Estrada - 2 years ago 72
Javascript Question

Copying a javascript array inside a class protoype function

I have this class on javascript:

function Node(board,x,y,t){
this.board = board;
this.x = x;
this.y = y;
this.playerTile = t;
this.oponentTile = getOponentTile(this.playerTile);
this.parent = null;
this.getChildren = getChildren;


and I´m using this function which copies the
variable (which is an array) to the
variable using

var getChildren = function() {
if(this.x==-1 && this.y ==-1){
var moves = getAllValidMoves(this.board,this.playerTile);
var tempBoard = this.board.slice();
var moves = getAllValidMoves(tempBoard,this.playerTile);

var children = [];
for(var i = 0;i<moves.length;i++){
var currentMove = moves[i];
var currentBoard = this.board.slice();
if(this.x==-1 && this.y ==-1){
children.push(new Node(currentBoard,currentMove[0],currentMove[1],this.playerTile));
children.push(new Node(currentBoard,currentMove[0],currentMove[1],this.oponentTile));

return children;

the problem is that after calling
both the
and the
variables are being modified.

Is there any way I can copy an array without it´s reference?

Answer Source

.slice() makes a shallow copy of the array, not a deep copy.

That means that if you have an array of objects and you use .slice() to make a copy of the array, it gives you a new array that is a first level copy. But the new array points to all the same objects as the first array. You can rearrange the copied array or remove elements from it and that will not affect the first array.

But, if you modify the objects in the array, it is the same objects in both arrays so making a modification to any object in the array (such as changing a property on the object) will be seen in both arrays.

If you want a full copy of the array and it's contents, then you have to make a deep copy which is a bit more complicated and can slightly depend upon what exactly you have in the array.

There are many different ways to make a deep copy. You can read about many of them in these references:

Most elegant way to clone a JavaScript object

Copying an array of objects into another array in javascript (Deep Copy)

Copying array by value in JavaScript

If you are guaranteed not to have any circular references in your array (where one object points to another which points back to it), then the simplest way to make a copy is this:

var tempBoard = JSON.parse(JSON.stringify(this.board));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download