我無法復制數組[重復]

[英]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