I have an array ele, and I want to populate another array arr with copies of ele, and then return the populated array. The JavaScript function I have is:
function foo(n) {
var arr = new Array(n);
var ele = [0,1];
for(var i=0;i<n;i++) {
arr[i] = ele;
}
return arr;
}
for e.g. foo(3), the output I want is [[0,1],[0,1],[0,1]], but I instead get the output: [#1=[0, 1], #1#, #1#] (using Firefox's Web Console). When I instead populate arr with [0,1] directly, as in
function fooNew(n) {
var arr = new Array(n);
for(var i=0;i<n;i++) {
arr[i] = [0,1];
}
return arr;
}
I get the correct output for fooNew(3): [[0,1],[0,1],[0,1]]. Why does my original function foo not give the same output as fooNew? That is: why can't I populate arr by assigning ele to arr[i], and instead have to populate it by assigning the content of ele directly to arr[i], to get the output I want?
======
Update: in light of Felix Kling's helpful answer, and after some googling, I found that by using slice(0), you can place a copy of ele into arr[i] rather than a reference to it. So the following modification of foo will give the desired output:
function foo(n) {
var arr = new Array(n);
var ele = [0,1];
for(var i=0;i<n;i++) {
arr[i] = ele.slice(0);
}
return arr;
}
elearray to all the positions onarr. So if you do something likex = foo(3); x[0].push(2);, now all the arrays on x have three elements (Because they're actually the same array)ele. Arrays, like objects{}are pointers to collections. So ifvar x = [1,2,3]and thenvar y = xand theny[0] = 9you will end up with an x of[9,2,3].