我无法复制数组[重复]

[英]i can't copy the array [duplicate]


This question already has an answer here:

这个问题在这里已有答案:

i can't copy the array.

我不能复制数组。

var Mycollection = new Array("James","Jonh","Mary");
var Mycollection2 = Mycollection;

Any change made in the first array is also taken in the second.

第一个数组中的任何更改也会在第二个数组中进行。

Mycollection.pop();
console.log(Mycollection.toString()) // ["James","Jonh"]
console.log(Mycollection2.toString())// ["James","Jonh"]

However this does not occur when I use variables of text type

但是,当我使用文本类型的变量时,不会发生这种情况

4 个解决方案

#1


2  

Arrays are objects, unlike the primitive types like string, int, etc ... variables that take objects correspond to references (pointer) for objects, rather than the object itself, so different variables can reference the same object. Variable of primitive type (string, int, etc.) are associated to values​​.

数组是对象,与原始类型(如string,int等)不同。采用对象的变量对应于对象的引用(指针),而不是对象本身,因此不同的变量可以引用同一个对象。基本类型的变量(字符串,整数等)与值相关联。

In your case you will have to clone your object array for have the same values​​.

在您的情况下,您将必须克隆您的对象数组以获得相同的值。

var Mycollection = new Array("James","Jonh","Mary");
var Mycollection2 = Mycollection.slice();

#2


2  

Javascript passes the Array by reference, to have separate Arrays do:

Javascript通过引用传递数组,以使单独的数组执行:

var Mycollection = new Array("James","Jonh","Mary");
var Mycollection2 = Mycollection.slice();

#3


1  

just use:

var Mycollection2 = Mycollection.slice(0);

var Mycollection2 = Mycollection.slice(0);

to copy the array

复制数组

#4


1  

You are actually copying an reference in your code,

您实际上正在复制代码中的引用,

var Mycollection = new Array("James","Jonh","Mary");
var Mycollection2 = Mycollection; // makes both Mycollection2 and Mycollection referring  to same array.

Use the Array.slice() method which creates a copy of part/all of the array.

使用Array.slice()方法创建部分/全部数组的副本。

var Mycollection1 = new Array("James", "Jonh", "Mary");
var Mycollection2 = Mycollection.slice();

Mycollection1.pop();
console.log(Mycollection1.toString()) // ["James","Jonh"]
console.log(Mycollection2.toString()) // ["James","Jonh", "marry"]

DEMO


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/02/21/ecbb8c550f9feec582b85f2d7c315201.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com