一:递归调用
<!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> <script> const Copy = (obj) => { if (obj === null && typeof obj !== "object") { return obj; } if (Object.prototype.toString.call(obj) === "[object Date]") { return new Date(obj); } if (Object.prototype.toString.call(obj) === "[object RegExp]") { return new RegExp(obj); } if (Object.prototype.toString.call(obj) === "[object Undefined]") { return new Error(obj); } // 判断对象是类 let newObj = Array.isArray(obj) ? [] : {} for (let item in obj) { if (typeof obj[item] === 'object') { newObj[item] = Copy(obj[item]) } else { newObj[item] = obj[item] } } return newObj }; const foo = { name: "rose", age: 9, job: { salary: 30, } } const newFoo = Copy(foo) console.log("新数组",newFoo) newFoo.job.salary = 100 console.log("修改后的新数组",newFoo) console.log("老数组:",foo,"新数组",newFoo) </script> </body> </html>
二:Js自带的函数structuredClone
<!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> <script> const foo = { name: "rose", age: 9, job: { salary: 30, } } const newFoo = structuredClone(foo) console.log("刚刚拷贝出来的新数组",newFoo) newFoo.job.salary =1000 console.log("老数组:",foo) console.log("修改后的新数组:",newFoo) </script> </body> </html>
三:第三方插件用Loadsh(cloneDeep)
const _ = require('lodash') var foo = { name: "rose", age: 99, job: { salary: 30, } } //用lodash实现深拷贝 var newFoo = _.cloneDeep(foo); console.log("刚刚拷贝出来的新数组",newFoo) //修改 newFoo.job.salary = 100 console.log("老数组:",foo) console.log("修改后的新数组:",newFoo)
标签:obj,log,newFoo,几种,数组,console,拷贝,foo,方法 From: https://www.cnblogs.com/zsbb/p/16827096.html