gpt4 book ai didi

javascript - 通过 for 循环扩充数组只保留最后一个对象?

转载 作者:搜寻专家 更新时间:2023-11-01 05:27:48 25 4
gpt4 key购买 nike

鉴于我的核心数据是这样的:

var data = [
{ name: "Student01", type: "received", grades: [ 12,12, 17, 17, 14.5, 10, 16, 15.5, 15.5, 15 ] },
{ name: "Student02", type: "given", grades: [ 11,6,15, 12 ] },
{ name: "Student03", type: "received", grades: [ 12,12, 17, 17, 14.5, 10, 16, 15.5, 15.5, 15 ] },
{ name: "Student04", type: "given", grades: [ 12,8,13, 12 ] }
];

给定一个我应该尊重的模板对象:

var template = {
text: "Hello guys !",
side: "negative",
name: "Some student",
x: [ 12.65, 17.92, 16.45 ],
orientation: "h"
};

然后我通过 for 循环构建一个 augmentedData:

var augmentedData = [];
for (var i=0; i<data.length;i++){
var trace = template,
student = data[i];
trace.text = "Step "+i;
trace.name = student.name;
trace.x = student.grades;
console.log(student, student.type)
trace.side = student.type == "given"?"negative":"positive";
console.log(vizGrades[i].type, trace, trace.side)
augmentedData.push(trace);
}

我的最终扩充数据由最后一个对象的 4 倍组成,它本身是扩充的:

console.log(JSON.stringify(augmentedData));

返回:

[
{"text":"Step 3","side":"negative","name":"Student04","x":[12,8,13,12],"orientation":"h"},
{"text":"Step 3","side":"negative","name":"Student04","x":[12,8,13,12],"orientation":"h"},
{"text":"Step 3","side":"negative","name":"Student04","x":[12,8,13,12],"orientation":"h"},
{"text":"Step 3","side":"negative","name":"Student04","x":[12,8,13,12],"orientation":"h"}
];

出了什么问题?如何解决?

编辑:预期输出:

[
{"text":"Step 0","side":"positive","name":"Student01","x":[12,12, 17, 17, 14.5, 10, 16, 15.5, 15.5, 15],"orientation":"h"},
{"text":"Step 1","side":"negative","name":"Student02","x":[11,6,15, 12],"orientation":"h"},
{"text":"Step 2","side":"positive","name":"Student03","x":[12,12, 17, 17, 14.5, 10, 16, 15.5, 15.5, 15],"orientation":"h"},
{"text":"Step 3","side":"negative","name":"Student04","x":[12,8,13,12],"orientation":"h"}
];

最佳答案

trace = template 行仅传递对来自模板的 trace 的引用,因此您在循环中一直使用同一个对象。

尝试

var template = function() {
return {
text: "Hello guys !",
side: "negative",
name: "Some student",
x: [ 12.65, 17.92, 16.45 ],
orientation: "h"
};
}

因此 trace 每次使用 trace = template(); 时都会成为一个新对象

Fiddle

关于javascript - 通过 for 循环扩充数组只保留最后一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50155239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com