HTML代码
<!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>深拷贝</title>
</head>
<body>
<script>
function deepCopy(obj) {
// 1.
// let res = Array.isArray(obj) ? [] : {}
// for (const [k, v] of Object.entries(obj)) {
// res[k] = typeof v === "object" ? deepCopy(v) : v
// }
// return res
// 2.简写
// return Object.entries(obj).reduce((t, cur, index, arr) => {
// let [k, v] = cur
// t[k] = typeof v === "object" ? deepCopy(v) : v
// return t
// }, Array.isArray(obj) ? [] : {})
// 3.一行
// return Object.entries(obj).reduce((t, [k, v]) => (t[k] = typeof v === "object" ? deepCopy(v) : v, t), Array.isArray(obj) ? [] : {})
// 非严格模式下。deepCope k
// console.log(arguments.callee===deepCopy)
// 4.一行
return Object.entries(obj).reduce((t, [k, v]) => (t[k] = typeof v === "object" ? arguments.callee(v) : v, t), Array.isArray(obj) ? [] : {})
}
let student = {
id: 1,
grade: { "math": 95, "english": 80 },
fridens: ["张三", "李四"]
}
let p = deepCopy(student)
p.fridens = []
p.grade.math=0
console.log(JSON.stringify(student, null, 2));
console.log(JSON.stringify(p, null, 2));
</script>
</body>
</html>