【问题标题】:How to iterate through a dynamically created array in jQuery?如何遍历 jQuery 中动态创建的数组?
【发布时间】:2020-04-10 16:42:54
【问题描述】:

我有一个通过 API 调用创建的数组。 这是我制作这个数组的方法-

var data5 = ko.observableArray(); /*Most important thing to make the data array observable otherwise it will not show the data of the REST API*/
var arrow = [];

function practiceData() {
  // var data = [];/**/

  $.getJSON("REST API").then(function(dataset) {
    $.each(dataset, function(index, value) {
      //console.table((dataset));
      //console.log(value.change);
      data5.push(value); // PUSH THE VALUES INSIDE THE ARRAY.
      arrow.push(value.change);
      console.log("arrow", arrow);
      arrow.forEach(function(value) {
        if (value == 0) {
          $("#triangle-down-small").hide();
          $("#triangle-up-small").hide();
          console.log("rgjak")
          console.log(value);
          //  document.getElementById("navTabBar").style.visibility = "none";
        } else if (value < 0) {
          //  $("#triangle-down-small").hide();
          $("#triangle-up-small").hide();
          console.log("hcdsb")
          console.log(value);
        }
      });
    });
  });
}

console.log(箭头)-

arrow (1) [0]
arrow (2) [0, 0]
arrow (3) [0, 0, -100]

JSON 响应结构-

[
{
        "change": 0,
        "count": 6,
        "duration": 4,
        "prevcount": 6,
        "subcategory": "Consultancy"
}
]

对于 if-else 条件,我无法遍历数组,.hide() 函数仅适用于 if 条件,不适用于 else-if。 任何帮助表示赞赏。 提前致谢。

【问题讨论】:

  • 任何控制台错误?此外,您分解的 sn-ps 也有些混乱。所有这些逻辑都在同一个地方。例如,第二个 sn-p 是 then() 调用的延续吗?
  • 另外,你的第一个 sn-p 并没有清楚地显示 json 响应结构是什么。
  • @t.niese, 第一个sn-p显示console.log("arrow", arrow)
  • @Taplar,我已经编辑了 sn-ps
  • 第一个片段仍然不清楚您的 json 响应是什么。

标签: javascript jquery oracle-jet


【解决方案1】:

仅供参考,在 $.each 之后移动循环。但是这样的编码没有意义。不好的做法

function practiceData() {
  $.getJSON("REST API").then(function (dataset) {
    $.each(dataset, function (index, value) {
      data5.push(value); // PUSH THE VALUES INSIDE THE ARRAY.
      arrow.push(value.change);
    });
    console.log("arrow", arrow);
    arrow.forEach(function (value) {
      if (value == 0) {
        console.log("rgjak");
        console.log(value);
      } else if (value < 0) {
        console.log("hcdsb");
        console.log(value);
      }
    });
  });
}

【讨论】:

  • 谢谢。但问题还是一样。请检查一下。
【解决方案2】:

数组 foreach 函数非常简单和基本,所以没有任何问题。 我猜你的问题是你的数据结构不一致或者你的代码有逻辑问题。 您应该确保始终检查您推入数组的值是否存在并且是数字。

例如

if (!value || typeof value.change === 'undefined') {
    return ;
}

另外,给定您的 json 响应数据,[0, 0, -100] if 和 else 语句都将运行,并且两个按钮都将被隐藏。 只要数组中有一个零,两个按钮都会被隐藏。

【讨论】:

    猜你喜欢
    • 2017-04-30
    • 2011-02-25
    • 1970-01-01
    • 2019-06-20
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    相关资源
    最近更新 更多