散列表,HashTable,也叫 HashMap。

    散列算法的作用是 尽可能快 地在数据结构中找到一个值。在之前的队列和链表中,如果要在数据结构中获得一个值(使用 get 方法),需要迭代整个数据结构来找到它。如果使用散列函数,就知道值的具体位置,因此能够快速检索到该值。

    散列函数的作用是给定一个键值,然后返回值在表中的地址。方法是简单地将每个键值中的每个字母的 ASCII 值相加,如下图所示。
    image.png

    散列函数的实现

    1. function defaultToString(item) {
    2. if (item === null) {
    3. return 'NULL';
    4. } if (item === undefined) {
    5. return 'UNDEFINED';
    6. } if (typeof item === 'string' || item instanceof String) {
    7. return `${item}`;
    8. }
    9. return item.toString();
    10. }
    11. function djb2HashCode(key) {
    12. const tableKey = defaultToString(key); // {1}
    13. let hash = 5381; // {2}
    14. for (let i = 0; i < tableKey.length; i++) { // {3}
    15. hash = (hash * 33) + tableKey.charCodeAt(i); // {4}
    16. }
    17. return hash % 1013; // {5}
    18. }