- 不拷贝 =》 赋值
举个例子:
let a = {
a:1,
b:2,
c:{
d:10,
e:20
}
}
let b = a;
b.a = 20;
console.log(a.a) // 20
直接赋值的话,对象是指向同一内存,所以修改对象b的属性,对象a的属性同时也会改变
- 浅拷贝 => Object.assign(),和解构赋值.
举个例子
let a = {
a:1,
b:2,
c:{
d:10,
e:20
}
}
let b = Object.assign({},a);
b.a = 20;
b.c.d = 20;
console.log(a.a) // 1
console.log(a.c.d) // 20
// 解构赋值方式同样只能拷贝到第一层
let b = {...a};
b.a = 20;
b.c.d = 20;
console.log(a.a) // 1
console.log(a.c.d) // 20
因为这种方法只拷贝了一层,内层的对象依然会指向同一内存,所以还会互相影响。
- 深拷贝 => JSON.stringify&JSON.parse,lodash
方法一: JSON.stringify&JSON.parse
举个例子:
let a = {
a:1,
b:2,
c:{
d:10,
e:20
}
}
// JSON.stringify(obj) 先将对象转换为字符串
// JSON.parse(str) 然后再将字符串转为对象。
let b = JSON.parse(JSON.stringify(a))
b.a = 20;
b.c.d = 20;
console.log(a.a) // 1
console.log(a.c.d) // 10
console.log(b.a) // 20
例子转自:
作者:小李子的一天
https://segmentfault.com/a/1190000016983370
JSON.stringify在转换Date,RegExp对象及function时会出现问题,同时也会忽略undefined、function
//date 类型
var o = new Date();
console.log(o.toString()); // Mon Nov 06 2017 11:23:35 GMT+0800 (China Standard Time) 本地标准时间
console.log(JSON.stringify(o)); // "2017-11-06T03:23:35.547Z" 国际标准时间
因为stringify默认调用的是Object的toJSON方法,所以重写Date的toJSON,然后stringify就是ok的。
Date.prototype.toJSON = function () {
return this.toLocaleString();
}
console.log(JSON.stringify(o)); // "11/6/2017, 11:23:35 AM"
// 同理RegExp
r1 = /\d+/;
console.log(JSON.stringify(r1)); // {}
RegExp.prototype.toJSON = function(){
return this.toString();
}
console.log(JSON.stringify(r1)); // "/\\d+/"
方法二:
借助Jquery或者lodash库
//jquery
let y = $.extend(true,{},x) //第一个参数 必须为true
//lodash库
let y = _.cloneDeep(x);