【问题标题】:How to copy or duplicate an array of arrays如何复制或复制数组数组
【发布时间】:2012-03-13 01:13:10
【问题描述】:

我正在尝试创建一个复制数组数组的函数。我试过 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 插件——所以我需要将它变成一个函数……递归并不是我最擅长的。

您的帮助将不胜感激!

干杯,

【问题讨论】:

标签: javascript


【解决方案1】:
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】:

例如:

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

根据 cmets 改进

【讨论】:

  • 将因null 而中断(null.pop 将抛出)。第一次检查应该类似于if (typeof obj != "object" || !obj)
  • 此外,对继承属性的处理存在问题 - JavaScript 中的“克隆”存在语义问题。
猜你喜欢
  • 2011-02-12
  • 1970-01-01
  • 2014-05-15
  • 2019-02-07
  • 1970-01-01
  • 2013-05-06
  • 2013-05-28
相关资源
最近更新 更多