【问题标题】:How to remove array element with loop in jquery如何在jquery中使用循环删除数组元素
【发布时间】:2021-09-05 20:12:40
【问题描述】:

我想删除基于if/else 条件的关联数组元素。我无法删除数组元素。这是我的代码。我只需要删除数组元素。

$(document).ready(function() {
  $("#submit").click(function() {
    var marks = $("#marks").val(); //getting student marks
    var data = <?php echo json_encode($records); ?>; // getting student record in array
    
    $.each(data, function(i, item) {
      var Isstudent = item.Isstudent
      var Ismandatory = item.Ismandatory
      var minMarks = item.min_value
      var maxMarks = item.max_value
      if (Isstudent == "1") {
        if (marks <= minMarks) {
          $this - > remove();
        } else {
          $this - > remove();
        }
      }
      console.log(item);
    });
  });
});

【问题讨论】:

  • 这里应该是什么$this
  • 另外,请提出正确 minimal reproducible examples 此类问题。在这种情况下,这意味着显示实际的示例数据,而不是 PHP 代码(我们这里的任何人都无法执行,因为我们缺少您的服务器端设置和数据。)
  • @Cbore: 我不知道如何删除我尝试使用 $this->remove(); 的数组元素
  • 请发布data的值。不过,您似乎只需要filter()
  • 注意,用你想要的元素创建一个新数组比从数组中“删除”元素要容易得多。如上所述,filter 有很大帮助。 $this-&gt;remove() 看起来像 php 代码 - 不要在 javascript 代码中混合 php 代码(以这种方式)。

标签: javascript php jquery arrays


【解决方案1】:

你可以只用那个条件过滤数据

$(document).ready(function() {
  $("#submit").click(function() {
    var marks = $("#marks").val(); //getting student marks
    var data = <?php echo json_encode($records); ?>; // getting student record in array
    data = data.filter(e => e.Isstudent !== 1) // any array item where Isstudent == 1 will be omitted.
    });
});

【讨论】:

    猜你喜欢
    • 2010-12-29
    • 2012-01-20
    • 2012-02-15
    • 2018-05-24
    • 1970-01-01
    • 2013-07-22
    • 2013-05-04
    • 2014-09-08
    相关资源
    最近更新 更多