从 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