两个对象,一个A 一个B
1 2 3 4 5 6 7 8 |
data() { return { dataA:{ a:1 }, dataB:'' } } |
将dataA的内容赋值给dataB,改变dataB里对象的值,发现dataA里的值也跟着变化了。为什么会出现这种情况呢?其实,这是一个引用传递而不是值传递,dataA和dataB指向的是同一个内存地址。
1 2 3 4 |
this.dataB = this.dataA; this.dataB.a = 5; console.log( this.dataA.a);//返回5 console.log( this.dataB.a);//返回5 |
如果我们不想让dataA的值跟着联动变化,应该怎么做呢?可以先把dataA转换成字符串,然后在转换成对象,代码如下:
1 2 3 4 |
this.dataB = JSON.parse(JSON.stringify(this.dataA)); this.dataB.a = 5; console.log( this.dataA.a);//返回1 console.log( this.dataB.a);//返回5 |
想了解更多,请自行搜索:深拷贝&&浅拷贝
谢谢分享,解决了我的问题