Is there a way to clone an array in jQuery?

This is my code:

var a=[1,2,3] b=$.clone(a) alert(b) 

Does jQuery have a clone method? How can I clone an array using jQuery?

+51
javascript jquery arrays clone
Sep 23 '10 at 4:37
source share
8 answers

Just use Array.prototype.slice .

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

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

+133
Sep 23 '10 at 4:39
source share

How about jQuery.merge ?

 copy = $.merge([], a); 
+9
Nov 27 '12 at 19:42
source share

Edit

b = $. clone (a) to b = $ (this) .clone (a) but doesn't work for a while

but reported

http://www.fusioncube.net/index.php/jquery-clone-bug-in-internet-explorer

Solution you use simple built-in javascript clone function

 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

Great alternative

  // Shallow copy var b = jQuery.extend({}, a); // Deep copy var b = jQuery.extend(true, {}, a); 

-John Resig

Check similar entry

  • What is the most efficient way to deeply clone an object in JavaScript?
+6
Sep 23 '10 at 4:58
source share

Here is how I did it:

 var newArray = JSON.parse(JSON.stringify(orgArray)); 

this will create a new deep copy that is not associated with the first (not a shallow copy).

also this, obviously, will not clone events and functions, but it’s good that you can do it in one line and it can be used for any object king (arrays, strings, numbers, objects ...)

+4
Apr 23 '14 at 13:33
source share

to 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

 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]​ 
+1
Sep 23 '10 at 4:41
source share

Another option is to use Array.concat:

 var a=[1,2,3] var b=[].concat(a); 
+1
Sep 23 '10 at 7:21
source share

 var a=[1,2,3] b=JSON.parse(JSON.stringify(a)); document.getElementById("demo").innerHTML = b; 
 <p id="demo"></p> 
0
Feb 11 '16 at 5:46
source share

ES6 Please use the distribution

 let arrayCopy = [...myArray]; 
0
Dec 18 '17 at 8:42 on
source share



All Articles