soin08
soin08

Reputation: 76

copy of an array JavaScript

I have some objects:

var obj1 = new Obj1(),
    obj2 = new Obj2(),
    ...

and two arrays:

objecs.push(obj1, obj2,...);
defaultObjects.push(obj1, obj2, ...);

During the game loop objects array changes, but defaultObjects does not. When the game needs to be restarted, I need to make objects equal to defaultObjects (just like it was in the beginning). if I do this:

objects = defaultObjects.slice(0)

does it mean that objects[0] and defaultObjects[0] are now pointing at the same object obj1, but there is no connection between objects and defaultObjects so I get what I need?

Upvotes: 0

Views: 148

Answers (1)

Li0liQ
Li0liQ

Reputation: 11264

That is correct. slice will return you a new array.
However, as you have mentioned, array elements will still be referring to the same objects. I.e. changing any object from one array will lead to its change in another.

Upvotes: 1

Related Questions