如何复制或复制数组数组

Jer*_*emy 6 javascript

我正在尝试创建一个复制数组数组的函数.我试过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;
};
Run Code Online (Sandbox Code Playgroud)

它工作,但搞砸了我正在使用的jQuery插件 - 所以我需要把它变成一个函数......并且递归不是我最强的.

非常感谢您的帮助!

干杯,

Chu*_*urk 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;
}
Run Code Online (Sandbox Code Playgroud)