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?
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?
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]
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
Another option is to use Array.concat:
var a=[1,2,3]
var b=[].concat(a);