问题
I'd hope to find an example code to do a deep copying of objects in ECMAScript5.
The copying should be able to clone
Nested objects
Nested arrays
Nested objects in arrays (clone each array item individually)
Note: jQuery.extend() does not seem to handle case 3). Also, I'd hope to do this in clean ECMAScript. Quick googling did not bring up any worthy implementations.
回答1:
I finally settled to jQuery.extend()
as I couldn't find other good implementations
http://api.jquery.com/jQuery.extend/
回答2:
if you want a one-liner (removes object refs by iterating through referenced objects to retrieve primitives, concats one large string, then parses the string into a new object with it's own primitive leaf nodes)
JSON.parse(JSON.stringify(obj))
or if you need to perform many copies
function deepCopy(o) {
var copy = o,k;
if (o && typeof o === 'object') {
copy = Object.prototype.toString.call(o) === '[object Array]' ? [] : {};
for (k in o) {
copy[k] = deepCopy(o[k]);
}
}
return copy;
}
performance comparison
回答3:
Use an emulation of the toSource method to copy the object:
<script type="text/javascript">
Object.prototype.getSource = function() {
var output = [], temp;
for (var i in this) {
if (this.hasOwnProperty(i)) {
temp = i + ":";
switch (typeof this[i]) {
case "object" :
temp += this[i].getSource();
break;
case "string" :
temp += "\"" + this[i] + "\""; // add in some code to escape quotes
break;
default :
temp += this[i];
}
output.push(temp);
}
}
return "{" + output.join() + "}";
}
var baz = {"alpha":{"beta":{"charlie": ["delta","epsilon",{"omega":"zeta"}]}}};
!!Object.prototype.toSource ? alert((baz).toSource() ) : alert((baz).getSource() );
</script>
来源:https://stackoverflow.com/questions/8092548/ecmascript5-deep-copy-of-object-and-arrays