最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to copy or duplicate an array of arrays - Stack Overflow

programmeradmin3浏览0评论

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.

I found this prototype method at .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.

Your help would be appreciated!

Cheers,

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.

I found this prototype method at http://my.opera./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.

Your help would be appreciated!

Cheers,

Share Improve this question asked Feb 22, 2012 at 16:59 JeremyJeremy 9252 gold badges12 silver badges22 bronze badges 2
  • 1 Be sure to declare "i" with var! Also it's risky to iterate over an array with a for ... in loop - much safer to use numeric indexes. – Pointy Commented Feb 22, 2012 at 17:02
  • See: stackoverflow./questions/565430/… – Diodeus - James MacFarlane Commented Feb 22, 2012 at 17:04
Add a ment  | 

2 Answers 2

Reset to default 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;
}

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 ments

发布评论

评论列表(0)

  1. 暂无评论