1

Strange situation in javascript:

var arr1=new Array();
var arr2=new Array();
arr1=[[1,2],[3,4]];
for (i=0;i<arr1.length;i++) {
 arr2[i]=arr1[i];
}
alert(arr2[1][0]); //-> 3
arr1[1][0]=10;
alert(arr2[1][0]); //-> 10

I do not understand why this is happening

Ufuk Hacıoğulları
  • 37,978
  • 12
  • 114
  • 156

3 Answers3

7

You build an array of array in line 3.

Within the for-loop you do not clone the inner array, but just copy a pointer to it. Hence, if you later on change the contents of an inner array in arr1 it also effects arr2.

No bug here anywhere.

If you want to clone the inner arrays, use something like this:

for (i=0;i<arr1.length;i++) {
 arr2[i] = arr1[i].slice(0);
}
Sirko
  • 72,589
  • 19
  • 149
  • 183
0

arr1 and arr2 are each arrays of arrays; hence, arr2 is built up of the same set of arrays as is arr1, so that assigning to an element of arr1[i] 'magically' shows up as the same element of arr2[i].

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

You have to clone the array....like this

var arr2 = arr1.slice(0);

check this

Community
  • 1
  • 1
Premshankar Tiwari
  • 3,006
  • 3
  • 24
  • 30