[英]Strange array.push in JS
I have simple code 我有简单的代码
sites_from_session = 12;
function function_name () {
var items_to_send = sites_from_session;
var template_name = jQuery('#new-site-template-name').val();
console.log(sites_from_session);
items_to_send.push(template_name);
console.log(sites_from_session);
}
function_name();
function_name();
function_name();
function_name();
function_name();
function_name();//...
The problem is that the push
method pushes value to both arrays 问题是
push
方法将值推入两个数组
Where i am wrong? 我哪里错了?
Arrays do not self clone in JavaScript. 数组不会在JavaScript中自动克隆。 When you say something like
当你说像
arr1 = arr2;
where both arr2
is a valid array, you haven't made an actual copy of arr2
. 如果两个
arr2
都是有效数组,则您尚未制作arr2
的实际副本。 All you've done is create a reference pointer to it for arr1
. 您要做的就是为
arr1
创建指向它的引用指针。 So when you make a change like 所以当你做出改变
arr1[0] = "some value";
you are (in essence) saying the same thing as 您(实质上)是在说与
arr2[0] = "some value";
To properly clone a separate copy you need to use this: 要正确克隆单独的副本,您需要使用以下命令:
var items_to_send = sites_from_session.slice();
This will return a new array that holds all of the items from the original array. 这将返回一个新数组,其中包含原始数组中的所有项目。
It is a very common Javascript problem. 这是一个非常常见的Javascript问题。 The arrays are not copied like this:
不会像这样复制数组:
var items_to_send = sites_from_session;
It merely copies the reference of the array to a new variable. 它仅将数组的引用复制到新变量。 In other words,
items_to_send
and sites_from_session
are two names pointing to the same array in RAM. 换句话说,
items_to_send
和sites_from_session
是指向RAM中同一阵列的两个名称。 If you want to make a copy of the array (called deep copying) rather than just another pointer (shallow copying), you need to use slice()
: 如果要复制数组(称为深度复制)而不是仅另一个指针(浅复制),则需要使用
slice()
:
//create a copy of the array
var items_to_send = sites_from_session.slice(0);
The rest of your code should work fine. 您的其余代码应该可以正常工作。
Possible duplication of this question: How do you clone an Array of Objects in Javascript? 这个问题的可能重复: 如何在Javascript中克隆对象数组?
You can learn more here: http://davidwalsh.name/javascript-clone-array 您可以在此处了解更多信息: http : //davidwalsh.name/javascript-clone-array
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.