Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a method to clone an array in jQuery?

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?

like image 819
zjm1126 Avatar asked Sep 23 '10 04:09

zjm1126


People also ask

How do you duplicate an array in JavaScript?

Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array under a new value variable.

How do you clone an object in jQuery?

To clone an element using jQuery, use the jQuery. clone() method. The clone() method clones matched DOM Elements and select the clones. This is useful for moving copies of the elements to another location in the DOM.


Video Answer


2 Answers

Just use Array.prototype.slice.

a = [1]; b = a.slice(); 

JSFiddle - http://jsfiddle.net/neoswf/ebuk5/

like image 172
meder omuraliev Avatar answered Sep 20 '22 11:09

meder omuraliev


What about the jQuery.merge ?

copy = $.merge([], a); 
like image 42
astgtciv Avatar answered Sep 20 '22 11:09

astgtciv