原生js中的深拷贝
将数据中所有的数据拷贝下来,对拷贝之后的数据进行修改不会影响到原数据 ,两个对象或数组不共享一块内存
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
| let obj={ abc:'123', def:[{a:1,b:2,c:3},{q:8,w:9}], qwe:{e:4,f:5} } function copyobj(oldobj){ let newObj=null if(oldobj instanceof Array){ newObj=[] oldobj.forEach(item => { newObj = copyobj(item) }); }else if(oldobj instanceof Object){ newObj={} for(var i in oldobj){ newObj[i]=copyobj(oldobj[i]) } }else { newObj=oldobj } return newObj } let news=copyobj(obj) console.log(news);
|
Object.create()
Object.create() 是es6新增的语法,实现的方式是通过深拷贝原型链的
Object.create : 创建一个新对象,使用现有的对象来提供新创建的对象的__proto__。
关于new Object和Object.create的区别
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| var a = { rep : 'apple' } var b = new Object(a) console.log("b = ",b) console.log("b.__proto__ = ",b.__proto__) console.log("b.rep = ",b.rep) console.log("a===b",a===b);
var a1 = { rep: 'apple' } var b1 = Object.create(a1) console.log("b1 = ",b1) console.log("b1.__proto__ = ",b1.__proto__) console.log("b1.rep = ",b1.rep) console.log("a1===b1",a1===b1);
|
函数库 lodash,提供 cloneDeep 实现
1.下载相关库
npm i –save lodash
2.在相关文件中引入
import _ from “lodash”
3.调用 _.cloneDeep() 方法实现深拷贝
1 2 3 4 5 6
| <script> import _ from "lodash" var objects = [{ 'a': 1 }, { 'b': 2 }]; var deep = _.cloneDeep(objects); console.log(deep[0] === objects[0]); </script>
|