<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JS深拷贝</title>
</head>
<body>
</body>
<script>
let obj = {
name: ‘张三‘,
age:22,
arr: [1,2,‘dadas‘],
where: {
country1: ‘中国‘,
country2: ‘府谷‘,
}
}
function deepClone(obj) {
if(obj === null || typeof obj !== ‘object‘) {
return obj;
}
let result;
if(obj instanceof Array) {
result = []
} else {
result = {}
}
for(let key in obj) {
if(obj.hasOwnProperty(key)) {
result[key] = deepClone(obj[key])
}
}
return result
}
let newObj = deepClone(obj);
console.log(newObj);
newObj.name = 999;
console.log(newObj);
console.log(obj);
</script>
</html>
原文:https://www.cnblogs.com/chailuG/p/14999969.html