Given this two arrays a and b:
var a = [1,2,3];
var b = a;
a.push(4);
console.log(b); /* [1,2,3,4] */
console.log(a); /* [1,2,3,4] */
Why isn't b equal with [1,2,3] ?
Given this two arrays a and b:
var a = [1,2,3];
var b = a;
a.push(4);
console.log(b); /* [1,2,3,4] */
console.log(a); /* [1,2,3,4] */
Why isn't b equal with [1,2,3] ?
The variable b
holds the reference to array a
. You need to copy the array instead use Array#slice
method to copy.
var a = [1, 2, 3];
var b = a.slice();
a.push(4);
console.log(b);
console.log(a);