Why can't I click inside an array and use it in a function argument in javascript?
Why are b and c not identical in the below code? What is the order of execution of the statement on line # 2?
var a = [1,2];
var b = new Array(a.push(1)); //[undefined, undefined, undefined]
var c = new Array(a); // [[1, 2, 1]]
The function .push()
returns the new length of the array, not the array itself. Thus, it is b
initialized to an empty array of 3 elements, because it .push()
returns 3 (after being added 1
to the end of the array a
).
You can also clone an array using a function slice
as an alternative to constructors. And use this path if you want it to a
remain unchanged.
var a = [1,2];
var b = a.slice();
b.push(1); // [[1, 2, 1]]
var c = b.slice(); // [[1, 2, 1]]