簡體   English   中英

如何從對象內部的數組中刪除特定元素?

[英]How to remove a specific element from an array which is inside of an object?

我正在學習如何通過購物清單練習來管理應用程序狀態。 按照說明,我在對象內部有一個數組,用於存儲添加的所有項目:

var state = {
    items: []
};

要修改state ,請使用以下功能:

var addItem = function(state, item) {
state.items.push(item);
};

稍后通過事件監聽器調用(並通過renderList添加到DOM,此處未顯示):

$('#js-shopping-list-form').submit(function(event){
    event.preventDefault();
    addItem(state, $('#shopping-list-entry').val());
    renderList(state, $('.shopping-list'));
});

如何從state對象內的數組中刪除特定項目? 本質上,當用戶單擊<button class="shopping-item-delete">時,我想顛倒上述順序。

這是最終解決方案的演示: https : //thinkful-ed.github.io/shopping-list-solution/

HTML

<body>

  <div class="container">

    <form id="js-shopping-list-form">
      <label for="shopping-list-entry">Add an item</label>
      <input type="text" name="shopping-list-entry" id="shopping-list-entry" placeholder="e.g., broccoli">
      <button type="submit">Add item</button>
    </form>

    <ul class="shopping-list">
    <li>
        <span class="shopping-item">apples</span>
        <div class="shopping-item-controls">
          <button class="shopping-item-toggle">
            <span class="button-label">check</span>
          </button>
          <button class="shopping-item-delete">
            <span class="button-label">delete</span>
          </button>
        </div>
      </li>
    </ul>
  </div>

  <script
  src="https://code.jquery.com/jquery-3.1.1.min.js"
  integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
  crossorigin="anonymous"></script>
<script type="text/javascript" src="app.js"></script>
</body>

您可以創建一個函數,如下所示:

var deleteItem = function(state, item) {
    var index = state.items.indexOf(item);
    if (index > -1) {
        state.items.splice(index, 1);
    }
};

請注意,Internet Explorer 7和8不支持indexOf方法。

如果您知道該項目的索引,則可以使用。 您可以通過項目的值確定索引

state.items.splice(indexOfItemToRemove, 1);

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

有兩種方法可以從數組中刪除元素:

shift將刪除開頭的第一項

pop將從末尾刪除最后一個項目。

splice使您可以在所需位置刪除元素

請注意,所有這些都將修改原始數組(它們在“原位”工作),而不是返回新數組。

您可以在項目上循環

var removeItem = function(state, item) {
  for(var i = state.items.length - 1; i >= 0; i--) {
    if(state.items[i] === item) {
       state.items.splice(i, 1);
       break;
    }
  }
};

暫無
暫無

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

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