簡體   English   中英

如果 Javascript 集中已存在值,如何刪除該值

[英]How to delete a value if it already exists in a Javascript Set

我有一個表,用戶可以在其中 select 一行,當他們這樣做時,行條目的 PK 將保存到一個集合中,但是,如果他們再次 select 它,我想從集合中刪除該值。 有誰知道這應該怎么做?

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該值,則將其刪除。 否則, add值添加到集合中。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM