做项目遇到一个问题,我需要在前端给对象进行循环赋值,然后转换成JSON字符串传输到后台,结果输出是重复值。
原代码
test(){
for(var i=0;i<=5;i++){
this.form.sid=i;
this.form.sname="小张"+i;
this.form.ssex="男";
this.form.sage=i;
this.arr.push(this.form);
}
console.log(JSON.stringify(this.arr));
}
输出结果
解决方法:每次添加到数组之后对对象属性进行清空
test() {
for (var i = 0; i <= 5; i++) {
this.form.sid = i;
this.form.sname = "小张" + i;
this.form.ssex = "男";
this.form.sage = i;
this.arr.push(this.form);
this.form = {
sid: null,
sname: null,
ssex: null,
sage: null
}
}
console.log(JSON.stringify(this.arr));
}
问题解决