Is there a method to clone an array in jQuery?
Just use Array.prototype.slice
.
a = [1];
b = a.slice();
JSFiddle - http://jsfiddle.net/neoswf/ebuk5/
What about the jQuery.merge ?
copy = $.merge([], a);
Change
b=$.clone(a) to b=$(this).clone(a) but it some time dont work
but is reported
http://www.fusioncube.net/index.php/jquery-clone-bug-in-internet-explorer
Solution you use simple inbuilt clone function of 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
A great alternative is
// Shallow copy
var b = jQuery.extend({}, a);
// Deep copy
var b = jQuery.extend(true, {}, a);
-John Resig
Check similar post
- What is the most efficient way to deep clone an object in JavaScript?
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 ...)
ES6 Please use spread
let arrayCopy = [...myArray];