javascript最新深度克隆对象方法
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
window.onload = function(){
var arr = [{"a":"a"},{"b":"b"}];
var clone = cloneObj(arr);
clone.a = "b";
console.log(clone);
console.log(arr);
}
function cloneObj(obj){ //obj 可能为[{a:"a"},{b:"b"}]和{c:"c"}
var newObj = obj.constructor == Array ?[]:{}; //如果JSON对象存在,则可以使用其方法JSON.stringify() 和JSON.parse()
if(typeof JSON == "object"){
var str = JSON.stringify(obj);
newObj = JSON.parse(str);
}else{ //如果JSON对象不存在,则需要递归实现克隆对象
for(var i in obj){
if(obj.hasOwnProperty(i)){ //arguments.callee() 和cloneObj()其实是一样的,arguments.callee()代码扩展性好
newObj[i] = typeof obj[i] == "object" ?arguments.callee(obj[i]):obj[i];
}
}
}
return newObj;
}
</script>
</head> <body>
</body>
</html>