javascript 通过引用传递解决方法 [英] javascript pass by reference workaround

查看:33
本文介绍了javascript 通过引用传递解决方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数组,var Animal = ["dog","cat","rat"];

然后我定义 var pets = animal;

然后我调用 pets.shift();

现在因为 javascript 是数组的传递引用,如果我现在调用 animals,我得到 ["cat","rat"].

now because javascript is pass-by-reference for arrays, if I now call animals, I get ["cat","rat"].

我的问题:如果我以后想以未修改的形式使用 animals,有什么办法可以解决这个问题吗?

My question: is there any way around this, if I would later like to use animals in its unmodified form?

推荐答案

术语说明:JavaScript never pass-by-reference(无论您听到多少次有人这么说).当你写下一行时:

A note on terminology: JavaScript is never pass-by-reference (no matter how many times you hear people say that it is). When you write the line:

var pets = animals;

您正在将 animalsvalue 分配给 pets.分配的值是对数组的引用,所以现在两个变量引用到内存中的同一个对象.(注意:这有点迂腐,但它也有正确的优点.)

You're assigning the value of animals to pets. The value that is assigned is a reference to an array, so now both variables refer to the same object in memory. (Note: this is a bit pedantic, but it also has the nice property of being correct.)

如果你想让这两个变量引用两个不同的数组,那么你需要创建一个原始数组的副本,并将对它的引用分配给 pets.在 JavaScript 中最常见的方法是利用一些数组方法(如 sliceconcat)创建它们所在数组的副本这一事实.重新调用:

If you want these two variables to refer to two different arrays, then you need to create a copy of the original array and assign a reference to that to pets. The most common way to do that in JavaScript is to take advantage of the fact that some array methods (like slice or concat) create a copy of the array on which they're called:

var pets = animals.concat();

不等式证明:

var arr = [];
arr1 = arr;
console.log(arr1 === arr); // true
console.log(arr1 === arr.concat()) // false

当然,你也可以自己进行复制:

Of course, you can also perform the copy yourself:

function copy(arr) {
    var i, len = arr.length, arr1 = new Array(len);
    for (i = 0; i < len; i += 1) {
        arr1[i] = arr[i];
    }
    return arr1;
}

确实,这可能要快得多,应该考虑用于非常大的数组.(在大多数情况下,只做最易读的事情.)

Indeed, this is probably a lot faster and should be considered for very large arrays. (In most cases, just do whatever is most readable.)

请注意,这些方法中的每一个都会创建原始数组的副本.如果数组包含对其他对象的引用,则这些引用将复制到新数组中(即原始数组和新数组都将引用相同的对象).另一方面,字符串和数字会直接复制到新数组中.

Note that each of these methods creates a shallow copy of the original array. If the array holds references to other objects, then those references are copied to the new array (i.e. both the original and the new array will refer to the same objects). Strings and numbers, on the other hand, are copied directly into the new array.

这篇关于javascript 通过引用传递解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆