前端学习(1693):前端系列javascript之深拷贝

    技术2022-08-11  117

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script src="./deepClone.js"> </script> </body> </html>

    deepClone.js

    console.log(111); const obj1 = { age: 20, name: 'xxx', address: { city: 'beijing' }, arr: ['a', 'b', 'c'] } const obj2 = deepClone(obj1); console.log(1); obj2.address.city = 'shanghai' /* console.log(obj1.address.city) */ obj2.arr[0] = 'a1' console.log(obj1.address.city); console.log(obj1.arr[0]) function deepClone(obj = {}) { if (typeof obj != 'object' || obj == null) { return obj } let result if (obj instanceof Array) { result = []; } else { result = {} } for (let key in obj) { if (obj.hasOwnProperty(key)) { //保证key不是原型的属性 result[key] = deepClone(obj[key]) //递归 } } return result; }

    运行结果

    Processed: 0.012, SQL: 9