I feel puzzled when I rethink of these two functions:
The first one goes like this:
var test = [1,2,3];
var ele = test[0];
ele= 2;
alert(test[0]);
The result is 1. I think this is obvious. But when I meet this:
var test = [{id:1},{},{}];
var ele = test[0];
ele.id = 2;
alert(test[0].id);
The result turns to be 2
So could anyone tell me that how the javascript work when it happens like this in the object array?
In JavaScript, objects are assigned by reference, rather than copied in memory. So if you assign an existing object to a different variable, both will point to the same object in memory. Modifications to either will therefore be reflected in both.
So in your example, executing
ele.id = 2;operates on the memory location holding the object attest[0]. The change to theidproperty of that object is reflected in both variables referencing it (test[0], ele)Note that if you had assigned the entire array
testtoele, modifying one of the array members would have been reflected in bothtest, elesince Arrays are objects in Javascript: