Reputation: 1
I tried the following code
var foo = [1,2];
var bar = foo;
bar[0] = 9;
console.log(foo[0],bar[0]); //the result is 9,9
How foo[0] can be 9?Please let me know this am stucked.Thanks in advance.
Upvotes: -1
Views: 58
Reputation: 114014
Arrays, objects and functions are references in javascript while numbers and strings are values. Therefore when you do:
var foo = [];
var bar = foo;
The variable bar
now points to foo
and both foo
and bar
refer to the same array.
If you want to copy an array, use Array.prototype.slice()
:
var bar = foo.slice();
Technically, the .slice()
method is meant to be used to return a subarray of an array but if called without any arguments it returns the whole array. The important thing to realize is that .slice()
returns a new array, not the original array. Which is why we use it to do a shallow copy of an array.
For objects you can use the Objcet.create()
function:
var foo = {};
var bar = Object.create(foo);
It should be noted that both .slice()
and Object.create()
creates shallow copies of the original. That is, if the array or object contains other arrays or objects then the contents are still references:
var foo = [[1,2],3];
var bar = foo.slice();
bar[1] = 100;
console.log(bar[1]); // 100
console.log(foo[1]); // 3
bar[0][0] = 200;
console.log(bar[0][0]); // 200
console.log(foo[0][0]); // also 200
If you want to do a deep copy you need to write a recursive function to build another array/object based on the original. Or if you don't mind a bit of temporarily wasted RAM you can convert them to JSON and back again:
var bar = JSON.parse(JSON.stringify(foo));
Or use a library that provides a deep-copy function like jQuery.
Upvotes: 1
Reputation: 534
foo
an array.bar
an reference to foo
bar
will really change foo
Now foo
IS bar
... and vice versa
Upvotes: 1
Reputation: 1343
In javascript, array are pass by reference. That means bar
is a pointer to the same object that foo
point to.
You need to add clone
method when you want to assign the variable by passing its value like following code
var foo = [1,2];
var bar = foo.clone();
bar[0] = 9;
console.log(foo[0],bar[0]); //the result is 1,9
Upvotes: 2