深拷贝,拷贝引用对象的引用对地址和栈。
先编辑deepClone.js文件
/* deepClone.js */
function deepClone(obj = {}) {
if (typeof obj !== 'object' || obj == null) {
return obj
}
let result
if (obj instanceof Array) {
result = []
} else {
result = {}
}
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
resutl[key] = deepClone(obj[key])
}
}
return result
}
在html中引入deepClone.js文件
<!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>Document</title>
</head>
<body>
<script src="./deepClone.js"></script>
<script>
let a = {
name: 'good',
list: ['1','2','3'],
duixiang: {
name: 'ab'
}
}
let b = deepClone(a)
a.duixiang.name = "bb"
console.log(b.duixiang.name) // ab
console.log(a.duixiang.name) // bb
</script>
</body>
</html>
总结:
- 深拷贝判断值类型和引用类型
- 注意判断是数组还是对象
- 递归
网友评论