javascript的hashCode函數(shù)實現(xiàn)代碼小結(jié)
為了使用的方便,稍稍再改良了一下
function hashcode(str) { var hash = 0, i, chr, len; if (str.length === 0) return hash; for (i = 0, len = str.length; i < len; i++) { chr = str.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash;}hashcode('this is a string')//-1853110172
這里接受的參數(shù)是一個 String,其它類型怎么辦?可以先做一個統(tǒng)一的處理,比如
hashcode(JSON.stringify(obj))序列化之后再使用 hashCode 函數(shù),基本所有類型數(shù)據(jù)都通吃,除了含有循環(huán)嵌套的對象。
PS:函數(shù)實現(xiàn)中有一行使用了 “|” 運算符,只是利用 Bitwise 運算符轉(zhuǎn)換參數(shù)為 32bit,用來確保結(jié)果是個 32位整數(shù)。
這里是Java的直接替代品字符串.hashCode()用Javascript實現(xiàn)的方法。
我編寫這個函數(shù)是為了滿足工作中的一個需求。顯然,后端工程師認為hashCode()是一個標準函數(shù)。這個項目的一個障礙不僅是如何翻譯Java中用來生成hashCode()的數(shù)學公式,還包括如何強制Javascript使用32位整數(shù)數(shù)學(這不是一個小的壯舉)。
幸運的是,我發(fā)現(xiàn)Java支持位運算符,這些運算符被限制在32位整數(shù)數(shù)學中。
下面是Javascript生成的字符串原型。使用這個原型,您可以簡單地對任何字符串調(diào)用.hashCode(),例如“some string”.hashCode(),并接收一個數(shù)字哈希代碼(更具體地說,是一個Java等效代碼),如1395333309。
String.prototype.hashCode = function(){var hash = 0;if (this.length == 0) return hash;for (i = 0; i < this.length; i++) {char = this.charCodeAt(i);hash = ((hash<<5)-hash)+char;hash = hash & hash; // Convert to 32bit integer}return hash;}
下面是其它網(wǎng)友的補充
hashCode = function(str){ var hash = 0; if (str.length == 0) return hash; for (i = 0; i < str.length; i++) { char = str.charCodeAt(i); hash = ((hash<<5)-hash)+char; hash = hash & hash; // Convert to 32bit integer } return hash;}djb2Code = function(str){ var hash = 5381; for (i = 0; i < str.length; i++) { char = str.charCodeAt(i); hash = ((hash << 5) + hash) + char; /* hash * 33 + c */ } return hash;}sdbmCode = function(str){ var hash = 0; for (i = 0; i < str.length; i++) { char = str.charCodeAt(i); hash = char + (hash << 6) + (hash << 16) - hash; } return hash;}loseCode = function(str){ var hash = 0; for (i = 0; i < str.length; i++) { char = str.charCodeAt(i); hash += char; } return hash;}
以上就是javascript的hashCode函數(shù)實現(xiàn)代碼小結(jié)的詳細內(nèi)容,更多關于javascript hashCode的資料請關注好吧啦網(wǎng)其它相關文章!
相關文章:
1. WML語言的基本情況2. python OpenCV學習筆記3. Python 多線程之threading 模塊的使用4. react axios 跨域訪問一個或多個域名問題5. python 實現(xiàn)rolling和apply函數(shù)的向下取值操作6. python利用platform模塊獲取系統(tǒng)信息7. CSS代碼檢查工具stylelint的使用方法詳解8. python求numpy中array按列非零元素的平均值案例9. Python過濾掉numpy.array中非nan數(shù)據(jù)實例10. Python的Tqdm模塊實現(xiàn)進度條配置
