Javascript 为什么我的对象只保存最后的数据
我正在创建两个对象,Javascript 为什么我的对象只保存最后的数据,javascript,object,push,Javascript,Object,Push,我正在创建两个对象,struct\u one和辅助的struct\u two,用于主存储数据。 在的帮助下添加数据后,按。struct\u one数组中的所有数据,都有最后一个数据 var struct_one={comments:[{comment:String}]}; var struct_two={comment:String}; 函数taskElementWork(){ this.createBlockSaveNew=函数(){ struct_two.comment=1+“红色”; s
struct\u one
和辅助的struct\u two
,用于主存储数据。
在的帮助下添加数据后,按
。struct\u one
数组中的所有数据,都有最后一个数据
var struct_one={comments:[{comment:String}]};
var struct_two={comment:String};
函数taskElementWork(){
this.createBlockSaveNew=函数(){
struct_two.comment=1+“红色”;
struct_one.comments.push(struct_two);
console.log(struct_one.comments[1].comment);/=1RED
struct_two.comment=2+“红色”;
struct_one.comments.push(struct_two);
console.log(struct_one.comments[2].comment);/=2RED
struct_two.comment=3+“红色”;
struct_one.comments.push(struct_two);
console.log(struct_one.comments[3].comment);/=3RED
console.log(struct_one.comments[1].comment);/=3RED->为什么!
}
}
测试=新taskElementWork();
test.createBlockSaveNew()代码>推送时使用相同的对象引用
您可以在赋值和按下之前获取一个新对象,如
function taskElementWork() {
var struct_two = { comment: '' };
struct_two.comment = 1 + "RED";
struct_one.comments.push(struct_two);
console.log(struct_one.comments[1].comment); // = 1RED
struct_two = { comment: '' };
struct_two.comment = 2 + "RED";
struct_one.comments.push(struct_two);
console.log(struct_one.comments[2].comment); // = 2RED
var struct_two = { comment: '' };
struct_two.comment = 3 + "RED";
struct_one.comments.push(struct_two);
console.log(struct_one.comments[3].comment); // = 3RED
}
更好的方法是使用函数构建结构,并为注释获取参数:
function taskElementWork() {
function buildStructure(comment) {
return { comment: comment };
}
struct_one.comments.push(buildStructure(1 + "RED"));
console.log(struct_one.comments[1].comment); // = 1RED
struct_one.comments.push(buildStructure(2 + "RED"));
console.log(struct_one.comments[2].comment); // = 2RED
struct_one.comments.push(buildStructure(2 + "RED"));
console.log(struct_one.comments[3].comment); // = 3RED
}
你能整理一下你的缩进吗?这可能是索引问题吗?可能从struct_one.comments[0].comment开始,然后转到1,然后在this.createBlockSaveNew
中的this
也可以。createBlockSaveNew
可能不会做您认为它做的事情。如果从struct_one.comments[0]开始,则注释结果将是“String(){[native code]}”,谢谢。我明白了。