gpt4 book ai didi

JavaScript .each 函数保存最后一个值

转载 作者:行者123 更新时间:2023-12-01 08:31:19 26 4
gpt4 key购买 nike

我有一个带有循环的函数,可以将数据保存在对象中,foreach 循环正在保存最后一个值

var n = new Array();
var weight = new Array();
var obj = {};
var as = [];
// var temp;

$("input:checked").each(function(){
temp = this.value;
// n.push(this.value);
obj['ids'] = temp;
obj['weight']= $("#weight"+temp).val();
as.push(obj);
delete temp;
});
console.log(as);

table image

console.log的结果是

(5) [{…}, {…}, {…}, {…}, {…}]

0: {ids: "298", weight: "1.00"}

1: {ids: "298", weight: "1.00"}

2: {ids: "298", weight: "1.00"}

3: {ids: "298", weight: "1.00"}

4: {ids: "298", weight: "1.00"}

这应该是

(5) [{…}, {…}, {…}, {…}, {…}]

0: {ids: "on", weight: "undefined"}

1: {ids: "4", weight: "1"}

2: {ids: "5", weight: "2"}

3: {ids: "6", weight: "3"}

4: {ids: "298", weight: "4"}

最佳答案

您在每个 push() 调用中向对象添加相同的引用。通过在循环内移动 var obj = {}; 来在每次迭代中创建一个新对象。另外,如果您在循环中定义 temp ,则不需要使用 delete temp - 无论如何,它在此实例中没有任何用处。

var n = [], weight = [], as = [];

$("input:checked").each(function() {
var temp = this.value;
var obj = {};
obj['ids'] = temp;
obj['weight'] = $("#weight" + temp).val();
as.push(obj);
});

console.log(as);

话虽如此,您可以通过使用 map() 来改进逻辑:

let as = $("input:checked").map(function() {
let temp = this.value;
return {
ids: temp,
weight: $("#weight" + temp).val()
}
}).get();

console.log(as);

关于JavaScript .each 函数保存最后一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60542021/

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