I've written the following JavaScript:
var myArray = ['a', 'b', 'c'];
var copyOfMyArray = myArray;
copyOfMyArray.splice(0, 1);
alert(myArray); // alerts ['b','c']
alert(copyOfMyArray); // alerts ['b','c']
var myNumber = 5;
var copyOfMyNumber = myNumber;
copyOfMyNumber = copyOfMyNumber - 1;
alert(myNumber); // alerts 5
alert(copyOfMyNumber); // alerts 4
This code declares a variable myArray
and sets it to an array value. It then declares a second variable copyOfMyArray
and sets it to myArray
.
It performs an operation on copyOfMyArray
and then alerts both myArray
and copyOfMyArray
. Somehow, when I perform an operation on copyOfMyArray
, it appears that the same operation is performed on myArray
.
The code then does the same thing with a number value: It declares a variable myNumber
and sets it to a number value. It then declares a second variable copyOfMyNumber
and sets it to myNumber
. It performs an operation on copyOfMyNumber
and then alerts both myNumber
and copyOfMyNumber
. Here, I get the expected behavior: different values for myNumber
and copyOfMyNumber
.
What is the difference between an array and a number in JavaScript that it seems changing an array changes the value of a copy of the array, where as changing a number does not change the value of a copy of the number?
I'm guessing that for some reason, the array is referred to by reference and the number by value, but why? How can I know what behavior to expect with other objects?
Everything is copied by reference except primitive data types (strings and numbers IIRC).
Create a filter of the original array in the arrayCopy. So that changes to the new array won't affect original array.
Hope it helps.
In JS, operator "=" copy the pointer to the memory area of the array. If you want to copy an array into another you have to use the Clone function.
For integers is different because they are a primitive type.
S.
Another approach for copying array into temporary variable can be typecasting/changing your array into string and then retrieving it.
E.g.
and now chnage in value of b will not be reflected on a
Your answer is here
Basically, the slice() operation clones the array and returns a shallow copy.
A clear Documentation can be found in the following link: Array.prototype.slice()