浅拷贝
* 注意浅拷贝的拷贝对象的格式
let test = {id: 1};let copy = Object.assign({}, test);test.id = 2;console.log(copy.id); // 1复制代码
let test = {id: 1};let copy = {...test};test.id = 2;console.log(copy.id); // 1复制代码
深拷贝
- JSON.parse(JSON.stringify(object))
- 此方法适用于该格式 let test = {id:1,name:{first_name:2,last_name:3}}
- 无法拷贝属性值undefined, 无法拷贝属性值函数,无法拷贝循环引用对象-直接报错。
let test = { id: 1, user_name: undefined, addr: function() {}, name: { first_name: 'simida', last_name: 'gg' }}let copy = JSON.parse(JSON.stringify(test))console.log(copy) // {id: 1,name: {first_name: 'simida',last_name: 'gg'}}复制代码
最后,浅拷贝,深拷贝都可以直接用lodash来处理