js 原生手写深拷贝
作者:互联网
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></body>
<script>
let obj = {
name: "zhangsan",
username: 1234,
password: "fdfe",
list: [3, 1, 2, [3, 2, 1], { name: "Lisi" }],
sex: undefined,
time: new Date(),
family: {
name: "王",
},
reg: /\d/,
fn: function () {
console.log("OK");
},
};
let obj2 = {};
function clone(obj2, obj) {
for (let key in obj) {
let value = obj[key];
console.log(value);
if (Object.prototype.toString.call(value) === "[object Array]") {
obj2[key] = [];
clone(obj2[key], value);
} else if (
Object.prototype.toString.call(value) === "[object Object]"
) {
obj2[key] = {};
clone(obj2[key], value);
} else {
obj2[key] = value;
}
}
}
clone(obj2, obj);
obj.family.name = "d";
obj.name = "dfdf";
obj.list.push(22);
obj.list[3].push(1);
obj2.list[4].name = "111";
console.log(obj);
console.log(obj2);
obj.fn();
obj2.fn()
</script>
</html>
标签:obj2,obj,name,value,js,key,console,手写,拷贝 来源: https://blog.csdn.net/Vue1024/article/details/123083392