如何复制或复制数组数组

How to copy or duplicate an array of arrays

本文关键字:复制数组 数组 复制 何复制      更新时间:2023-09-26

我正在尝试制作一个复制数组数组的函数。我尝试了blah.slice(0);但它只复制参考文献。我需要做一个复制品,使原件完好无损。

我在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;
};

它很有效,但把我正在使用的jQuery插件搞砸了——所以我需要把它变成一个函数。。。递归并不是我最擅长的。

非常感谢您的帮助!

干杯,

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;
}

例如:

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;
}

根据评论改进