从 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。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP