views:

142

answers:

5

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?

+4  A: 

Just use Array.prototype.slice.

a = [1];
b = a.slice();
meder
This is synonymous with `slice(0)` ?
Peter Ajtai
@Peter Ajtai - yeah.
meder
Thanks meder. ....... The only thing to watch out for, is that Arrays are objects, so you can attach properties and methods... like `var a=[1,2,3]; a.foo = function() { alert(this); };` With `slice()` any attached properties and methods aren't copied, so you couldn't do `b.foo()`... I only bring it up, since jQuery's `.clone()` does include a deep copy option. For example: http://jsfiddle.net/B2LQL/ .......... But this is pretty much a corner case in the context of this question.
Peter Ajtai
A: 

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]​
Reigel
This is just in case you've attached other properties to the array in addition to the values in the array? (as opposed to just using `slice(0)`)?
Peter Ajtai
@Peter - `slice(0)` is good. I'm just showing another way of solving it. ;)
Reigel
A: 
var a=[1,2,3]
var b=[];
jQuery.extend(b,a);
alert(b);
Praveen Prasad
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

JapanPro
A: 

Another option is to use Array.concat:

var a=[1,2,3]
var b=[].concat(a);
Mike Ratcliffe