方法一:
每次需要对temp重新赋值时,重新定义新的temp空对象,这样再对temp赋值并不会改变原来的temp值
var submitObj = []; var temp = {}; temp.id = 1; temp.name = 'a'; submitObj.push(temp); var temp = {}; // 注释掉这句的话,submitObj中temp.id=1会随着temp.id=2的修改而改变 temp.id = 2; temp.name = 'b'; submitObj.push(temp); console.log(submitObj);
方法二:
定义数组submitObj
var submitObj = [];
定义submitObj里面的每个对象 temp
var temp = {};
给temp对象赋值
temp.id = 1; temp.name = 'a';
直接把temp对象push进去submitObj的话,下次修改temp时之前push的对象也会跟着修改,所以先转换一下再push
var c = Object.assign({}, temp) submitObj.push(c);
以后再更改temp,也是转换后再push,则temp的更改不会改变submitObj中之前push的值
temp.id = 2; temp.name = 'b'; var c = Object.assign({}, temp) submitObj.push(c);
可使用console.log(submitObj);查看数组的值
方法三:
var obj1 = {a:1,b:2}; var obj2 = {b:3,c:4}; var obj3 = {}; var obj4 = Object.assign(obj3,obj1,obj2); console.log(obj4); obj3.b = 11; console.log(obj4);
obj1以及obj2的改变并不会使得obj4的值发生改变,但obj3的值的改变会使obj4的值改变。若要使得obj4的值不受任何外界对象改变,可以这样
方法四:
var obj1 = {a:1,b:2}; var obj2 = {b:3,c:4}; var obj4 = Object.assign({},obj1,obj2); console.log(obj4); obj1.b = 11; obj2.b = 11; console.log(obj4);
以上,obj4的值不会随任何外界对象的改变而发生改变