從 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-6 月 -2020

1K+ 瀏覽量

開啟你的 職業

完成課程以獲得認證

開始
廣告
© . All rights reserved.