Skip to content Skip to sidebar Skip to footer

Javascript Array.push On Clone Array Modify Original Array

I found a really weird (for me) problem I have this global variable ARRAY var A = [1,2,3,4] then inside a function, I made local var and assign previous global var to it function

Solution 1:

What happens is that you do not copy the array you just reference it. You can use the method slice to create a copy of it:

var X = A.slice();

Do mind that you can use this approach only with primitive values. Check this if you need to deal with objects How do you clone an Array of Objects in Javascript?

Solution 2:

Your arrays aren't cloned: assigning a variable does not clone the underlying object.

You can shallow-clone an array using the slice method:

var cloned = original.slice();

But array and object items within the array are not cloned using this method. Numbers and strings are cloned, however, so this should work fine for your case.

Solution 3:

An array in JavaScript is also an object and variables only hold a reference to an object, not the object itself. Thus both variables have a reference to the same object.

Post a Comment for "Javascript Array.push On Clone Array Modify Original Array"