<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>深拷贝</title>
</head>
<body>
<script>
// npm install http-server -g 安装服务
// http-server -p 9999 设置端口
// 深拷贝
const obj = {
age: 20,
name: '小丽',
address: {
city: '北京'
},
arr: ['a', 'b']
}
const newObj = deepClone(obj)
newObj.address.city = '上海'
console.log(newObj.address.city)
// 深拷贝函数
function deepClone(obj = {}) {
// obj是null,或者不是对象数组,就直接返回
if (typeof obj !== 'object' || obj == null) {
return obj
}
// 初始化返回结果
let result
if (obj instanceof Array) {
result = []
} else {
result = {}
}
for (let key in obj) {
//保证key是自己的不是原型的
if (obj.hasOwnProperty(key)) {
//递归
result[key] = deepClone(obj[key])
}
}
// 返回结果
return result
}
</script>
</body>
</html>
网友评论