Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

深浅拷贝 #11

Open
Qhappyman opened this issue May 31, 2019 · 1 comment
Open

深浅拷贝 #11

Qhappyman opened this issue May 31, 2019 · 1 comment

Comments

@Qhappyman
Copy link
Owner

Qhappyman commented May 31, 2019

//赋值 都改变
//深浅拷贝

		var a ={
			b :1,
			c:{
				book:"you"
			}
		}
		//var c = a;
		//c.b = 3; //a.b = 3; 复制的地址,共用一个堆内容
		//object.assign()
		//var b = Object.assign({},a);
		//console.log(b); //同a
		//a.b = 5;
		//console.log(b.b);//1
		//a.c.book = "ni";
		//console.log(b.c.book) //"ni"

		var a ={
			b :1,
			c:{
				book:"you"
			}
		}
		//var d = Object.assign({},a.c);
		//console.log(d);//同a.c
		//a.c.book = "ni";
		//console.log(d.book);//you
		//自我认为,Object.assign()是深拷贝,实际上,Object.saaign()只进行了第一层的拷贝,拷贝第二层的引用地址,所以是浅拷贝
		//let e = {...a};//和Object.assign()一样
		//深拷贝
		//JSON.parse(JSON.stringify(object))
		let f =JSON.parse(JSON.stringify(a));
		a.b = 5;
		a.c.book = "my";
		console.log(f);//b:1 c.book:you 无影响
		//弊端:忽略Symbol,undefined,function
		let g = {
			a:undefined,
			b:Symbol("guo"),
			c:()=>console.log(1),
			d:1
		}
		let m = JSON.parse(JSON.stringify(g));
		console.log(m);//d:1
		//循环引用报错
		// let obj = {
  //   		a: 1,
  //   		b: {
  //       		c: 2,
  //  				d: 3
  //   		}
		// }
		// obj.a = obj.b;
		// obj.b.c = obj.a;

		// let b = JSON.parse(JSON.stringify(obj));
		// Uncaught TypeError: Converting circular structure to JSON
		//new Date()转化不正确
		// let data = new Date();
		// console.log(JSON.stringify(data));
		// console.log(JSON.parse(JSON.stringify(data)));
		//解决方法:转化为字符串或时间戳
		let date = (new Date()).valueOf();
		JSON.stringify(date);
		JSON.parse(JSON.stringify(date));
		//正则出错
		let obj = {
    		name: "muyiy",
    		a: /'123'/
		}
		console.log(obj);
		// {name: "muyiy", a: /'123'/}

		let b = JSON.parse(JSON.stringify(obj));
		console.log(b);
		// {name: "muyiy", a: {}}

和原数据是否指向同一对象 第一层数据为基本数据类型 原数据中包含子对象
//赋值 是 改变会使原数据一同改变 改变会使原数据一同改变
//浅拷贝 否 改变不会使原数据一同改变 改变会使原数据一同改变
//深拷贝 否 改变不会使原数据一同改变 改变不会使原数据一同改变

@Qhappyman
Copy link
Owner Author

好久以前写的,比较乱,没有整理

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant