從 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。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP