js对象的深度克隆

时间:2022-07-07 14:12:29
 <!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<title>js对象的深度克隆</title>
</head> <body>
<script type="text/javascript">
var cloneObj = function(obj) {
var str, newobj = obj.constructor === Array ? [] : {};
if (typeof obj !== 'object') {
return;
} else if (window.JSON) {
str = JSON.stringify(obj), //系列化对象
newobj = JSON.parse(str); //还原
} else {
for (var i in obj) {
newobj[i] = typeof obj[i] === 'object' ?
cloneObj(obj[i]) : obj[i];
}
}
return newobj;
};
</script>
</body> </html>