從 Javascript 雜湊表中移除元素


要刪除元素,我們只需要找到它們並使用一個簡單的 splice 函式呼叫來刪除它們,這個呼叫會就地刪除陣列中的元素。

讓我們看看相同的實現 − 

示例

remove(key) {
   let hashCode = this.hash(key);

   for (let i = 0; i < this.container[hashCode].length; i++) {
      // Find the element in the chain
      if (this.container[hashCode][i].key === key) {
         this.container[hashCode].splice(i, 1);
         return true
      }
   }
   return false;
}

你可以使用 − 來測試這一點

示例

let ht = new HashTable();

ht.put(10, 94); ht.put(20, 72);
ht.put(30, 1);
ht.put(21, 6);
ht.put(15, 21);
ht.put(32, 34);

console.log(ht.get(20));
console.log(ht.remove(20));
console.log(ht.get(20));
console.log(ht.remove(20));

輸出

這將輸出 −

{ key: 20, value: 72 }
true
undefined
false

第一次它返回 true,因為它已被成功找到並刪除。第二次,因為不在,所以 remove 函式返回 false。

更新日期:15-Jun-2020

1K+ 次瀏覽

開啟你的職業生涯

透過完成本課程獲得認證

開始學習
廣告
© . All rights reserved.