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>
var obj1 = {
name: 'laowang',
age: 18,
do: function () {
console.log('study')
},
hobby: ['唱', '跳', 'rap', [1, 2, 3]],
}
function checkType(obj) {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
}
function deepClone(obj) {
if (checkType(obj) === 'object') {
var newObj = {}
} else if (checkType(obj) === 'array') {
var newObj = []
} else {
return obj
}
for (var key in obj) {
newObj[key] = deepClone(obj[key])
}
return newObj
}
var obj2 = deepClone(obj1)
console.log(obj1)
console.log(obj2)
console.log(obj2 === obj1)
console.log(obj2.hobby === obj1.hobby)
console.log(obj2.hobby[3] === obj1.hobby[3])
</script>
</body>
</html>