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 afor ... 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
2 Answers
Reset to default 5function 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