JavaScript/HASH:修订间差异
来自康健生活
创建页面,内容为“== 标题文本 == == HASH CODE == 实现一: {{leftrightflex|<syntaxhighlight lang="javascript"> String.prototype.HASHCode = function(){ let hash = 0; for (let i = 0; i < this.length; i++) { hash = ((hash << 5) - hash) + this.charCodeAt(i); // Convert to 32bit integer hash = hash & hash; } return hash; } console.log("Hello World!".HASHCode());</syntaxhighlight>|{{consoleout|<pre>-969099747 </pre>}}}}” |
|||
| 第13行: | 第13行: | ||
} | } | ||
console.log("Hello World!".HASHCode());</syntaxhighlight>|{{consoleout|<pre>-969099747 | console.log("Hello World!".HASHCode());</syntaxhighlight>|{{consoleout|<pre>-969099747 | ||
</pre>}}}} | |||
实现二: | |||
{{leftrightflex|<syntaxhighlight lang="javascript"> | |||
String.prototype.HASHCode = function(){ | |||
const MAX_VALUE = 0x7fffffff; | |||
const MIN_VALUE = -0x80000000; | |||
let hash = 0; | |||
for (let i = 0; i < this.length; i++) { | |||
hash = hash * 31 + this.charCodeAt(i); | |||
if(hash > MAX_VALUE || hash < MIN_VALUE) hash &= 0xFFFFFFFF; | |||
} | |||
return hash; | |||
} | |||
console.log("Hello World!".HASHCode()); </syntaxhighlight>|{{consoleout|<pre>-969099747 | |||
</pre>}}}} | </pre>}}}} | ||
2023年3月28日 (二) 07:26的版本
No categories