Skip to content

深浅拷贝 #11

Open
Open
@Qhappyman

Description

@Qhappyman

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

		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: {}}

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions