+ 2
Can somebody explain to me how this works?
var arr1 = [1, 2, 3] ; var arr2 = arr1 ; arr1[0] = 4 ; Why is document.write(arr2[0]) 4? Isn't it supposed to be 1?
12 Answers
+ 9
You linked those two arrays together so when arr1[0] changes, arr2[0] gets the same value.
+ 7
I think this happens only on object linking (array is an object)
+ 6
Simply arr2 is copying the address of arr1. The reference is copying. So you can access arr2 as like arr1.
+ 3
My Javascript is a bit rusty, but if it's the same as in C it works like this:
By saying arr2 = arr1 you basically point arr2 to exactly the same array as arr1, it won't just copy the values. So if you change something at arr1 it will also be changed in arr2.
The arr variable only holds the position of the array, not it's values!
+ 3
@Gavin Christians Yeah it appeared in one of our challenges. I KNEW the answer and what's wrong with asking the explanation out of it? I don't see anything wrong with that? It's not that I just merely asked for the answer out.
+ 3
Nothings wrong with it, I meant no offence. I was just pulling your leg, cause it's friendly competition ;) Hope to challenge you again soon, this time I'll win
+ 2
xd this is confusing. However, if var a = 10 ; var b = a ; a = 20 ; b will maintain its value, which is 10. Why JS? Why?
+ 2
Makes sense, anyway thanks! I wonder if this works with null...
+ 2
As I said, you arr1 and arr2 variable hold the position of the array in memory, not it's actual values.
By setting arr2 = arr1 they both point at the same position, meaning the same array.
Normal variables just hold a value, so if you set b = a, b will now have the value of a.
+ 2
Hey...I never test this thing!
+ 2
lol you're looking for an answer to beat me again cheeze. Not fair but okay because we all need to learn
+ 2
I'm going to bed again, I shouldn't have woken up this early.