简体   繁体   中英

Javascript array strange behaviour

By js convention and as far as I know

  • Primitive datatypes are worked under pass by value and
  • complex datatypes are worked under pass by reference

If it so

var ary = [1,2,3];
var dupAry = ary;
//Now I am going to rewrite the ary variable as follows
ary = [3,4,5];

Now I log the values of ary and dupAry it logs different values. By its standard both array should return the vaues.

  1. so why it return different array values?

Another scenario

    var ary = [1,2,3];
    var dupAry = ary;
    //No I gonna apply splice method to the ary.
    ary.splice(0,1);

Now both array return same values and it works fine with its standard.

  1. Finally why its doesn't applied with first scenario?
 var dupAry = ary; 

This assigns a reference to the array that ary points to to dupAry . Both ary and dupAry now hold a reference which points to the same array object. If you now assign something else to ary , then dupAry will continue to hold a reference which points to the array object, and ary will now hold some other value.

By assigning something to a variable, you're not modifying the object that variable already holds; you're modifying the object reference that variable holds.

 ary.splice(0,1) 

This modifies the actual object that both variables points to, so both see the change.

When you do this:

ary = [3,4,5];

... you aren't altering an array: you are destroying the previous reference and creating a brand new variable* with a brand new array. See the difference with:

ary.push(99);

(*) Well, not really a new variable, of course—I didn't know how to word it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM