ในการลบองค์ประกอบ เราเพียงแค่ต้องค้นหาและลบออกโดยใช้การเรียกฟังก์ชัน 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 สิ่งนี้คืนค่าเป็นจริงในครั้งแรกเนื่องจากพบและลบสำเร็จ ครั้งต่อไป เนื่องจากไม่ปรากฏ ฟังก์ชันลบจึงคืนค่าเป็นเท็จ