Assign value not reference in javascript [duplicate]

混江龙づ霸主 提交于 2020-05-12 11:06:35

问题


I am having a little problem assigning objects in javascript.

take a look at this sample code that reproduces my problem.

var fruit = {
   name: "Apple"
};

var vegetable = fruit;
vegetable.name = "potatoe";
console.log(fruit);

it logs

Object {name: "potatoe"}

How can I assign the value not the reference of an object to another object?


回答1:


You can use Object.assign:

var fruit = {
   name: "Apple"
};

var vegetable = Object.assign({}, fruit);
vegetable.name = "potatoe";
console.log(fruit);


来源:https://stackoverflow.com/questions/40133582/assign-value-not-reference-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!