Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การลบข้อมูลจาก Hash Table ใน JavaScript


ในการลบข้อมูล เราเพียงแค่ค้นหาข้อมูลนั้นๆ และลบออกโดยใช้ splice function ที่จะลบ element ใน array แบบ in-place

มาดูการนำไปใช้งานกัน:

ตัวอย่างโค้ด

remove(key) {
  let hashCode = this.hash(key);
  for (let i = 0; i < this.container[hashCode].length; i++) {
    // ค้นหา element ใน 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 เพราะพบและลบสำเร็จ ครั้งที่สองคืนค่า false เพราะข้อมูลไม่มีอยู่แล้ว