【问题标题】:JavaScript .each function saving last valueJavaScript .each 函数保存最后一个值
【发布时间】:2020-06-17 21:18:35
【问题描述】:

我有一个带有循环的函数,可以将数据保存在对象中, 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"}

【问题讨论】:

  • 你能分享你正在使用的这段代码的 HTML 吗?

标签: javascript jquery html json object


【解决方案1】:

您在每个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);

【讨论】:

  • 你提出了一个更好的答案,所以我删除了我的
  • 谢谢,这有效,我会将此标记为正确答案
  • 没问题,很高兴为您提供帮助
猜你喜欢
  • 2012-04-04
  • 2015-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-03
  • 1970-01-01
  • 1970-01-01
  • 2021-11-19
相关资源
最近更新 更多