Possible Duplicate:
Generate a Hash from string in Javascript/jQuery
谁能推荐一个用(浏览器兼容的)JavaScript 编写的简单(即数十行代码,而不是数百行)哈希函数?理想情况下,我想要一些东西,当将字符串作为输入传递时,会产生类似于 32 个字符的十六进制字符串的东西,这是 MD5、SHA1 等的典型输出。它不必是加密安全的,只是合理地抵抗冲突. (我最初的用例是 URL,但将来我可能想在其他字符串上使用它。)
这个我自己没验证过,大家可以看看这个JavaScript implementation of Java's String.hashCode() method .看起来相当短。
With this prototype you can simply call .hashCode()
on any string, e.g. "some string".hashCode()
, and receive a numerical hash code (more specifically, a Java equivalent) such as 1395333309.
String.prototype.hashCode = function() {
var hash = 0;
for (var i = 0; i < this.length; i++) {
var char = this.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
2022 年编辑:
人们早就接受了modifying built-in prototypes is bad practice ,所以你应该使用一个简单的函数:
/**
* Returns a hash code from a string
* @param {String} str The string to hash.
* @return {Number} A 32bit integer
* @see http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
*/
function hashCode(str) {
let hash = 0;
for (let i = 0, len = str.length; i < len; i++) {
let chr = str.charCodeAt(i);
hash = (hash << 5) - hash + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
}