简体   繁体   English

有没有一种方法可以在jQuery中克隆数组?

[英]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? jQuery没有'克隆'方法吗? How can I clone an array using jQuery? 如何使用jQuery克隆数组?

Just use Array.prototype.slice . 只需使用Array.prototype.slice

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

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

jQuery.merge呢?

copy = $.merge([], a);

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 ...) 这显然也不会克隆事件和函数,但你可以在一行中做到这一点,它可以用于任何对象之王(数组,字符串,数字,对象......)

Change 更改

b=$.clone(a) to b=$(this).clone(a) but it some time dont work b = $ .clone(a)b = $(this).clone(a)但是有些时候不行

but is reported 但据报道

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

Solution you use simple inbuilt clone function of javascript 解决方案你使用简单的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 -ConroyP

A great alternative is 一个很好的选择是

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

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

-John Resig -John Resig

Check similar post 检查类似的帖子

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]​

Another option is to use Array.concat: 另一种选择是使用Array.concat:

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

 var a=[1,2,3] b=JSON.parse(JSON.stringify(a)); document.getElementById("demo").innerHTML = b; 
 <p id="demo"></p> 

ES6请使用点差

let arrayCopy = [...myArray];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM