简体   繁体   English

JavaScript Array.push()

[英]Javascript Array.push()

I am new to Javascript and now suffer from one problem on Array.push and this in prototype. 我刚接触Javascript,现在在Array.push上遇到一个问题,在原型中也遇到了这个问题。

Here is my code: 这是我的代码:

function Ball(array) {
    this.array = array; 
}

Ball.prototype.allArray = []; // this is a property shared among ALL Ball object, though here I just create one object... 
Ball.prototype.addArray = function() {
    this.allArray.push(12); 
}

Ball.prototype.changeArray = function() {
    var array = this.array; 
    var allArray = this.allArray; 

    for (var i = 0; i < allArray.length; i++) {
        array.push(allArray[i]); 
    }
    // Array.prototype.push.apply(array, allArray); // same result as above 

    alert(array.length); // 3 Expected

    /*         PROBLEM          */
    alert(this.array.length); // 3, expected 2 Why 3? We just change array NOT this.array... 
}

var ball = new Ball([123, 198]); 
ball.addArray(); 
ball.changeArray(); 

As stated in the above code, I've a problem on why this.array.length = 3 , but not 2 . 如上面的代码所述,我对为什么this.array.length = 3而不是2

In the changeArray method, I've been changing only array values, not array.length . changeArray方法中,我仅更改数组值,而不更改array.length That means the value of this.array should remain unchanged. 这意味着this.array的值应保持不变。 Therefore, this.array.length should be 2 . 因此, this.array.length应该为2

Are there any things wrong in my thinking? 我的想法有什么问题吗? In addition, how can I get this.array.length = 2; 另外,我怎么能得到this.array.length = 2; while continue to get array.length = 3 ? 同时继续获取array.length = 3吗?

PS You may also take a look at this running code in JSFiddle . PS您还可以在JSFiddle中查看此正在运行的代码。

this.array; //inside changeArray() points to the same array which you passed to new Ball([123, 198]) ; //内部changeArray()指向您传递给new Ball([123, 198]) changeArray()的同一数组;

var array = this.array; // this makes array point to same array. //这会使数组指向同一数组。 So changes to array will also change your array. 因此,更改数组也会更改您的数组。

With

 var array = this.array; 
 var allArray = this.allArray; 

you effectively set pointers to the properties of the this object. 您可以有效地将指针设置this对象的属性。 So, everything you seemingly do with array you actually do with this.array . 因此,您似乎array所做的所有事情实际上都与this.array

If you want to work on a copy of this.array you should do 如果您要处理this.array副本this.array应该这样做

var array=this.array.slice(0);

instead. 代替。 You should be aware though that even this approach will generate the new array-elements only on one level. 您应该知道,即使这种方法也只能在一个级别上生成新的数组元素。 If you were working with an array of arrays then the inside arrays (or any other objects) will again only be pointers to the original ones. 如果使用数组数组,则内部数组(或任何其他对象)将再次仅是原始数组的指针

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

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