如何復制或復制數組數組

[英]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