问题
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