javascript - 如果值已存在于 Javascript 集合中,如何删除该值

标签 javascript jquery html set

我有一个表,用户可以在其中选择一行,当他们这样做时,行条目的主键被保存到一个集合中,但是,如果他们再次选择它,我想从集合中删除该值。有人知道应该怎么做吗?

JS & JQ

let bill = new Set()

$("body").on('click', '#food_table tbody tr', function() {
  var key = $(this).find(".key").text();
  var keyInt = parseInt(key)
  console.log(keyInt)

  bill.forEach(function(item) {
    if (item === keyInt) {
      bill.delete(item);
    } else {
      bill.add(keyInt)
    }
  });

  console.log(bill)
});

当我运行它时,我没有收到任何错误,但“账单”集仍然是空的。

必要时用 html

<table class="table table table-borderless" id="food_table">
      <thead>
        <tr>
          <th></th>
          <th>Description</th>
          <th>Price</th>
        </tr>
      </thead>
      <tbody>
        {% for objects in object %}
        <tr>
          <td class="key">{{ objects.food_item.pk }}</td>
          <td>{{ objects.food_item.food }} </td>
          <td>{{ objects.food_item.price }}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>

有谁知道如何解决这个问题?

最佳答案

您不需要遍历 Set。如果设置has值,删除它。否则,将值添加到集合中。

if (bill.has(keyInt))
  bill.delete(keyInt)
else
  bill.add(keyInt)

关于javascript - 如果值已存在于 Javascript 集合中,如何删除该值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58707980/

相关文章:

javascript - react .js : Can certain components be made SSR-rendering only?

javascript - 将字符串格式的数组转换为 JavaScript 数组

javascript - jQuery 不适用于按钮事件

jquery 与 asp.net mvc 对话框

javascript - JQuery index() 为第一个元素返回 1 而不是 0

javascript - 使用 Python mechanize 使用 javascript 处理特定表单

javascript - Uncaught Error : [$injector:modulerr] & Uncaught ReferenceError: app is not defined

c# - 在 C# 和 javascript 中避免重复代码的任何想法

html - 缩放 PDF 以适合 iFrame

html - CSS 表格行在表格单元格内未 100% 扩展