1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| let user = { name: "lisi", obj: { height: "188", age: "18", }, }; function copy1(obj) { let res = {}; for (const key in obj) { res[key] = typeof obj[key] === "object" ? copy1(obj[key]) : obj[key]; } return res; } let newuser1 = copy1(user); newuser1.obj.age = 19; console.log(JSON.stringify(newuser1, null, 2), "拷贝后"); console.log(JSON.stringify(user, null, 2), "拷贝前");
let arrdata = { name: "lisi", info: { age: "18", height: "188", }, data: [ { id: "1", title: "css", }, ], }; function copy2(obj) { let res = obj instanceof Array ? [] : {}; for (const [key, value] of Object.entries(obj)) { res[key] = typeof value === "object" ? copy2(value) : value; } return res; } let newarrdata = copy2(arrdata); newarrdata.data[0].title = "6666"; console.log(JSON.stringify(newarrdata, null, 2), "拷贝后"); console.log(JSON.stringify(arrdata, null, 2), "拷贝源");
function deelClone(obj) { return JSON.parse(JSON.stringify(obj)); } let obj1 = { name: "张三", age: 16, obj: { sex: "男", height: 188, }, data: [ { name: "sdfsdf", }, ], }; let obj2 = deelClone(obj1); obj1.age = 30; obj2.obj.sex = "女";
console.log(obj1);
console.log(obj2);
|