老师,我依葫芦画瓢,按照数组中深克隆的相关理解,重新写了个对象深克隆 ,不知道是否有问题,烦请指教!谢谢!
相关代码:
<!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>deepClone</title> </head> <body> <script> var obj1 = { a: 1, b: 2, c: [3,4], d:{ e:11, g:[5,6] } }; function deepClone(obj) { var obj2 = {}; for (var k in obj) { if (Array.isArray(obj[k])) { var result = []; for(var i = 0; i < obj[k].length; i++){ result.push(obj[k][i]); }; obj2[k] = result; } else if (typeof (obj[k]) == 'object') { obj2[k] = deepClone(obj[k]); } else { obj2[k] = obj[k]; } } return obj2; } var obj3 = deepClone(obj1); obj3.c.push(5); obj3.d.f = 111; obj3.d.g.push(999); console.log(obj1); console.log(obj3); console.log(deepClone(obj1)); </script> </body> </html>
12
收起
正在回答 回答被采纳积分+1
2回答
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星