我正在尝试从我循环的现有数组创建一个新的对象数组,但我最终只得到最后一个值.我明白为什么会这样,只是不确定采取什么方法来获得理想的结果.
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"}]
Shai Aharoni.. 7
将您的代码更改为:
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,因为它存在于外部循环范围内.将它移动到循环的内部块时,可以在每次迭代时使用所需的值添加新对象.
将您的代码更改为:
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,因为它存在于外部循环范围内.将它移动到循环的内部块时,可以在每次迭代时使用所需的值添加新对象.