如何复制或复制数组数组

[英]How to copy or duplicate an array of arrays


I'm trying to make a function that duplicates an array of arrays. I tried blah.slice(0); but it only copies the references. I need to make a duplicate that leaves the original intact.

我正在尝试创建一个复制数组数组的函数。我试过blah.slice(0);但它只复制引用。我需要复制一份原版完整的原件。

I found this prototype method at http://my.opera.com/GreyWyvern/blog/show.dml/1725165

我在http://my.opera.com/GreyWyvern/blog/show.dml/1725165找到了这个原型方法

Object.prototype.clone = function() {
  var newObj = (this instanceof Array) ? [] : {};
  for (i in this) {
    if (i == 'clone') continue;
    if (this[i] && typeof this[i] == "object") {
      newObj[i] = this[i].clone();
    } else newObj[i] = this[i]
  } return newObj;
};

It works, but messes up a jQuery plugin I'm using - so I need to turn it onto a function... and recursion isn't my strongest.

它工作,但搞砸了我正在使用的jQuery插件 - 所以我需要将它转换为函数...并且递归不是我最强的。

Your help would be appreciated!

非常感谢您的帮助!

Cheers,

2 个解决方案

#1


5  

function clone (existingArray) {
   var newObj = (existingArray instanceof Array) ? [] : {};
   for (i in existingArray) {
      if (i == 'clone') continue;
      if (existingArray[i] && typeof existingArray[i] == "object") {
         newObj[i] = clone(existingArray[i]);
      } else {
         newObj[i] = existingArray[i]
      }
   }
   return newObj;
}

#2


2  

For example:

clone = function(obj) {
    if (!obj || typeof obj != "object")
        return obj;
    var isAry = Object.prototype.toString.call(obj).toLowerCase() == '[object array]';
    var o = isAry ? [] : {};
    for (var p in obj)
        o[p] = clone(obj[p]);
    return o;
}

improved as per comments

根据评论改进

关注微信公众号

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/02/22/1099bda8e5ba2584851a5c3ccc3c73ec.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com