简体   繁体   English

函数内的JavaScript .push()覆盖了全局变量

[英]JavaScript .push() inside function is overriding global variable

I have the following problem with .push() method: 我有.push()方法的以下问题:

var myArray = ["a", "b", "c", "d"];

function add(arr) {
    arr.push("e");
    return arr;
}

add(myArray);

// myArray is now  ["a", "b", "c", "d", "e"]

Why it overrides myArray ? 为什么它会覆盖myArray Can't understand that... 无法理解......

Arrays in Javascript (and most other languages) are passed by reference. Javascript(和大多数其他语言)中的数组通过引用传递。

When you write add(myArray) , you are passing a reference to the same Array instance that the global myArray variable refers to. 当您编写add(myArray) ,您将传递对全局myArray变量引用的同一Array实例的引用。
Any changes to the array object will be visible through both references. 通过两个引用都可以看到对数组对象的任何更改。

To copy the actual array instance, write add(myArray.slice()); 要复制实际的数组实例,请编写add(myArray.slice()); .
Note that this will not copy the objects inside of it. 请注意,这不会复制其中的对象。

If you need to be able to nest arrays, then I'd change the .add() function to have the .concat() duplicate the Array into a variable, .push() the new value into the new Array, and return it. 如果你需要能够嵌套数组,那么我将改变.add()函数让.concat()将Array复制到变量中,将.push()新值复制到新数组中,然后返回它。

function add(arr) {
    var newArr = arr.concat(); // duplicate
    newArr.push("e");      // push new value
    return newArr;         // return new (modified) Array
}

You could use concat() as well, and return the new array it creates. 您也可以使用concat() ,并返回它创建的新数组。

var myArray = ["a", "b", "c", "d"];

function add(arr) {
    return arr.concat("e");
}
var newArray = add(myArray);

console.log( newArray );  // ["a", "b", "c", "d", "e"]
console.log( myArray );   // ["a", "b", "c", "d"]

So instead of two methods .slice() then .push() , you accomplish it with one .concat() . 因此,用一个.concat()完成它,而不是两个方法.slice()然后.push() .concat()

This also gives you the benefit of passing another Array instead of a string, so: 这也为您提供了传递另一个Array而不是字符串的好处,因此:

return arr.concat(["e","f"]);

would give you: 会给你:

// ["a", "b", "c", "d", "e", "f"]

instead of: 代替:

// ["a", "b", "c", "d", ["e", "f"] ]

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

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