深拷贝和浅拷贝的问题

  1. 不拷贝 =》 赋值

举个例子:

let a = {
	a:1,
	b:2,
	c:{
		d:10,
		e:20
	}
}
let b = a;
b.a = 20;
console.log(a.a) // 20

直接赋值的话,对象是指向同一内存,所以修改对象b的属性,对象a的属性同时也会改变


  1. 浅拷贝 => 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

因为这种方法只拷贝了一层,内层的对象依然会指向同一内存,所以还会互相影响。


  1. 深拷贝 => 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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值