对象赋值后原对象值随之变化

问题:一个对象赋值给另一个对象后,新对象的值更改原对象的参数值随之变化(即改变新对象的值会影响原对象值)

var a = {name: 'siryang'};
var b = a;
b.name = 'maolin';
console.log(a.name); //maolin

解决方法

 方法一:

var a = {name: 'siryang'};
var b = JSON.parse(JSON.stringify(a));
b.name = 'maolin';
console.log(a.name); //maolin

 方法二:

var a = {name: 'siryang'};
var b = Object.assign({},a);
b.name = 'maolin';
console.log(a.name); //maolin

 

你可能感兴趣的:(JavaScript)