8

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.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.

Your help would be appreciated!

Cheers,

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. Commented Feb 22, 2012 at 17:02
  • See: stackoverflow.com/questions/565430/… Commented Feb 22, 2012 at 17:04

2 Answers 2

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; } 
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Will break for null (null.pop will throw). The first check should be something like if (typeof obj != "object" || !obj).
Also, questionable handling of inherited properties - "clone" in JavaScript has problematic semantics.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.