JavaScript 散列表(HashTable)

來源:互聯網
上載者:User

標籤:return   ide   strong   索引值   log   nbsp   key   pen   his   

TypeScript方式實現源碼

// 特性:// 散列演算法的作用是儘可能快地在資料結構中找到一個值。 在之前的章節中, 你已經知道如果// 要在資料結構中獲得一個值(使用get方法) ,需要遍曆整個資料結構來找到它。如果使用散列// 函數,就知道值的具體位置,因此能夠快速檢索到該值。散列函數的作用是給定一個索引值,然後// 傳回值在表中的地址// ? put(key,value):向散列表增加一個新的項(也能更新散列表)// ? remove(key):根據索引值從散列表中移除值// ? get(key):返回根據索引值檢索到的特定的值// ? loseloseHashCode(key):散列函數// ? put(key):
 1 /** 2  * 散列表 3  * @desc 與Set類相似,ECMAScript 6同樣包含了一個Map類的實現,即我們所說的字典 4  */ 5 class HashTable { 6     private table = []; 7     public put(key, value) { 8         let position = HashTable.loseloseHashCode(key); 9         console.log(‘position‘ + ‘-‘ + key);10         this.table[position] = value;11     }12     public remove(key) {13         this.table[HashTable.loseloseHashCode(key)] = undefined;14     }15     public get(key) {16         return this.table[HashTable.loseloseHashCode(key)];17     }18     private static loseloseHashCode(key) {19         let hash = 0;20         for (let i = 0; i < key.length; i++) {21             hash += key.charCodeAt(i);22         }23         return hash % 37;24     }25 }
散列表 HashTable

 

JavaScript方式實現源碼

 1 /** 2  * 散列表 3  * @desc 與Set類相似,ECMAScript 6同樣包含了一個Map類的實現,即我們所說的字典 4  */ 5 var HashTable = (function () { 6     function HashTable() { 7         this.table = []; 8     } 9     HashTable.prototype.put = function (key, value) {10         var position = HashTable.loseloseHashCode(key);11         console.log(‘position‘ + ‘-‘ + key);12         this.table[position] = value;13     };14     HashTable.prototype.remove = function (key) {15         this.table[HashTable.loseloseHashCode(key)] = undefined;16     };17     HashTable.prototype.get = function (key) {18         return this.table[HashTable.loseloseHashCode(key)];19     };20     HashTable.loseloseHashCode = function (key) {21         var hash = 0;22         for (var i_1 = 0; i_1 < key.length; i_1++) {23             hash += key.charCodeAt(i_1);24         }25         return hash % 37;26     };27     return HashTable;28 }());
散列表 HashTable

JavaScript 散列表(HashTable)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.