【问题标题】:For loop only calling on the last array in the object in some places and not othersFor 循环仅在某些地方调用对象中的最后一个数组,而不在其他地方调用
【发布时间】:2020-02-23 21:43:36
【问题描述】:

我正在从 JSON 文件调用对象数组:

if (results !=null && results.value !=null {
  for (var i = 0; i < result.value.length; i++) {
    time = results.value[i].starttime;
    place = results.value[i].location;
    who = results.value[i].attendee;
    console.log("first test", time, place, who);
  }
}
function(error) {
   alert ("Error here" + error.message);
}
$(#homepagetime).html(time);
$(#homepageplace).html(place);
$(#homepagewho).html(who);
console.log("second test", time, place, who);

名为“first test”的控制台日志以下列方式成功显示来自json的每个结果:

12:00 India Gandhi
14:00 England Elizabeth
16:00 USA Obama

这正是我正在寻找的,但是当我使用下面的代码在 homepagetime、homepageplace 和 homepagewho div 中显示结果时,什么都没有出现。对于控制台日志“第二次测试”,我只取回对象中的第一个数组,而不是剩余的例如:

12:00 India Gandhi

它显然只调用对象中的第一个数组,但我不明白为什么考虑到 for 循环指定所有数组。我还在学习 JavaScript。

【问题讨论】:

  • 什么是results.value
  • @ASDFGerte results.value 是我正在调用的 json 的名称
  • 您需要在问题中输入results
  • 您确定第二个console.log 记录的是第一个元素,而不是最后一个元素吗?
  • 我的错,是的!它只记录最后一个。但这是为什么呢? @ASDFGerte

标签: javascript arrays json object for-loop


【解决方案1】:

您的(显示)代码必须在循环内,您可以使用字符串连接或 append() 函数将数据附加到 div 元素

for (var i = 0; i < results.value.length; i++) {
    time = results.value[i].starttime;
    place = results.value[i].location;
    who = results.value[i].attendee;
    console.log("first test", time, place, who);
    $(#homepagetime).append(time + '<br>');
    $(#homepageplace).append(place + '<br>');
    $(#homepagewho).append(who + '<br>);
}

【讨论】:

    【解决方案2】:

    显示结果的代码在循环之外,这意味着它只会执行一次,而不是像预期的那样对每个数组元素执行。在每个循环迭代中设置变量时间、地点和谁,最后剩下的就是最后一次迭代的结果。请注意,即使您将显示代码移动到循环内部,html 函数也会替换元素上当前的内容,因此,每次循环迭代都会替换结果,并且您最终会得到与当前相同的内容。我建议要么连接结果,要么为每个结果动态创建一个新元素。

    【讨论】:

      【解决方案3】:

      您应该在分配值的循环中附加 html。由于关闭,您将在循环外获得最后一个值。

      for (var i = 0; i < result.value.length; i++) {
          time = results.value[i].starttime;
          place = results.value[i].location;
          who = results.value[i].attendee;
          console.log("first test", time, place, who);
          $(#homepagetime).html(time);
          $(#homepageplace).html(place);
          $(#homepagewho).html(who);
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-31
        • 2021-12-26
        • 2020-02-23
        • 1970-01-01
        • 2012-10-20
        • 1970-01-01
        相关资源
        最近更新 更多