简体   繁体   English

Javascript数组奇怪的行为

[英]Javascript array strange behaviour

By js convention and as far as I know 据js约定,据我所知

  • 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. 现在,我记录ary和dupAry的值,它记录不同的值。 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 . 这将对ary指向dupAry的数组分配一个引用。 Both ary and dupAry now hold a reference which points to the same array object. arydupAry现在都拥有一个指向同一数组对象的引用。 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. 如果现在为ary分配其他内容,则dupAry将继续保存指向数组对象的引用,而ary现在将保留其他值。

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. (*)当然,不是真正的新变量,我不知道该怎么写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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