<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
</body>
<script>
function deepCopy(obj){
//确定入参是数组还是对象
var objArray = Array.isArray(obj) ? []:{};
//obj存在,且类型为对象
if(obj && typeof obj === 'object'){
//遍历对象属性
for(key in obj){
//判断对象属性是否属于自身
if(obj.hasOwnProperty(key)){
//判断obj子属性是否为对象,如果是,递归操作,否 将对象保存
if(obj[key] && typeof obj[key] === 'object'){
objArray[key] = deepCopy(obj[key])
}else{
objArray[key] = obj[key]
}
}
}
}
return objArray;
}
var obj1 = {
nan:1,
bei:null,
dong:undefined,
xi:{
xinan:2,
xibei:function(){
let b = 2
}
},
fn:function(){
let a = 1;
},
a:[1,2]
}
var obj2 = deepCopy(obj1)
console.log(obj1)
obj2.xi.xinan = 5;
console.log(obj2)
</script>
</html>