Javascript 有没有一种方法可以在 jQuery 中克隆数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3775480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a method to clone an array in jQuery?
提问by zjm1126
This is my code :
这是我的代码:
var a=[1,2,3]
b=$.clone(a)
alert(b)
Doesn't jQuery have a 'clone' method? How can I clone an array using jQuery?
jQuery 没有“克隆”方法吗?如何使用 jQuery 克隆数组?
回答by meder omuraliev
Just use Array.prototype.slice
.
a = [1];
b = a.slice();
JSFiddle - http://jsfiddle.net/neoswf/ebuk5/
JSFiddle - http://jsfiddle.net/neoswf/ebuk5/
回答by astgtciv
回答by Chtiwi Malek
This is how i've done it :
我就是这样做的:
var newArray = JSON.parse(JSON.stringify(orgArray));
this will create a new deep copy not related to the first one (not a shallow copy).
这将创建一个与第一个无关的新深拷贝(不是浅拷贝)。
also this obviously will not clone events and functions, but the good thing you can do it in one line and it can be used for any king of object (arrays, strings, numbers, objects ...)
这显然也不会克隆事件和函数,但是你可以在一行中完成它的好事,它可以用于任何对象之王(数组、字符串、数字、对象......)
回答by Pramendra Gupta
Change
改变
b=$.clone(a)to b=$(this).clone(a)but it some time dont work
b=$.clone(a)到b=$(this).clone(a)但它有一段时间不起作用
but is reported
但被举报
http://www.fusioncube.net/index.php/jquery-clone-bug-in-internet-explorer
http://www.fusioncube.net/index.php/jquery-clone-bug-in-internet-explorer
Solutionyou use simple inbuilt clone function of javascript
解决方案您使用javascript的简单内置克隆功能
var a=[1,2,3];
b=clone(a);
alert(b);
function clone(obj){
if(obj == null || typeof(obj) != 'object')
return obj;
var temp = obj.constructor();
for(var key in obj)
temp[key] = clone(obj[key]);
return temp;
}
-ConroyP
-ConroyP
A great alternative is
一个很好的选择是
// Shallow copy
var b = jQuery.extend({}, a);
// Deep copy
var b = jQuery.extend(true, {}, a);
-John Resig
-约翰·雷西格
Check similar post
检查类似的帖子
回答by Mike Ratcliffe
Another option is to use Array.concat:
另一种选择是使用 Array.concat:
var a=[1,2,3]
var b=[].concat(a);
回答by Reigel
try
尝试
if (!Array.prototype.clone) {
Array.prototype.clone = function () {
var arr1 = new Array();
for (var property in this) {
arr1[property] = typeof (this[property]) == 'object' ? this[property].clone() : this[property]
}
return arr1;
}?
}
use as
用于
var a = [1, 2, 3]
b = a;
a.push(4)
alert(b); // alerts [1,2,3,4]
//---------------///
var a = [1, 2, 3]
b = a.clone();
a.push(4)
alert(b); // alerts [1,2,3]?
回答by zloctb
ES6 Please use spread
ES6 请使用传播
let arrayCopy = [...myArray];
回答by Pradeep Kumar
var a=[1,2,3]
b=JSON.parse(JSON.stringify(a));
document.getElementById("demo").innerHTML = b;
<p id="demo"></p>