我正在尝试从我正在循环的现有数组创建一个新的对象数组,但我最终只得到了最后一个值。我明白为什么会这样,只是不确定采取什么方法来获得理想的结果。
var existingThing = ["one","two","three"];
var thingtoAdd = {};
var newthing = [];
for (var i = 0; i < existingThing.length; i++) {
thingtoAdd.key = existingThing[i];
thingtoAdd.value = existingThing[i];
thingtoAdd.selected = "true";
newthing.push(thingtoAdd);
}
console.log(JSON.stringify(newthing));
我最终得到了:
[{"key":"three","value":"three","selected":"true"},
{"key":"three","value":"three","selected":"true"},
{"key":"three","value":"three","selected":"true"}]
答案 0 :(得分:6)
将您的代码更改为:
var existingThing = ["one","two","three"];
var newthing = [];
for (var i = 0; i < existingThing.length; i++) {
var thingtoAdd = {};
thingtoAdd.key = existingThing[i];
thingtoAdd.value = existingThing[i];
thingtoAdd.selected = "true";
newthing.push(thingtoAdd);
}
console.log(JSON.stringify(newthing));
您不断重写相同的对象thingtoAdd,因为它存在于外部循环范围内。将它移动到循环的内部块时,在每次迭代时添加一个具有所需值的新对象。
答案 1 :(得分:0)
按
后清空thingToAdd对象for (var i = 0; i < existingThing.length; i++) {
thingtoAdd.key = existingThing[i];
thingtoAdd.value = existingThing[i];
thingtoAdd.selected = "true";
newthing.push(thingtoAdd);
thingToAdd = {};
}
答案 2 :(得分:0)
每次推动将对象添加到数组newthing
中时,您只推送该对象的引用“thingtoAdd”,因此当您在第二次或第三次迭代中更新对象时您正在更新对象本身的for
循环,因此每次都会更新具有该对象引用的数组,因此该数组将具有两个具有相同值或最后更新值的“thingtoAdd”对象对象。
因此清空对象意味着您每次都要创建对象的实例。在for
循环中放置一个调试器并检查“newthing”数组,你可以找到答案。
var obj = { val: 5 }
function increment(obj) {
obj.val++
}
increment(obj)
当您调用上述函数obj
时,它将每次递增,但
function increment(val) {
val++
}
val = 5
increment(val)
alert(val)
在上述情况val
中将是相同的。区别在于,在第一个示例中obj
未更改,但它引用的数据被修改,而在第二个示例中,变量val
被更改。
答案 3 :(得分:-2)
var existingThing = ["one","two","three"];
var newthing = [];
for (var i = 0; i < existingThing.length; i++) {
var thingtoAdd = {};
thingtoAdd.key = existingThing[i];
thingtoAdd.value = existingThing[i];
thingtoAdd.selected = "true";
newthing.push(thingtoAdd);
}
console.log(JSON.stringify(newthing));