Generate a Hash from string in Javascript

前端 未结 22 1413
不知归路
不知归路 2020-11-22 03:34

I need to convert strings to some form of hash. Is this possible in JavaScript?

I\'m not utilizing a server-side language so I can\'t do it that way.

22条回答
  •  离开以前
    2020-11-22 04:12

    EDIT

    based on my jsperf tests, the accepted answer is actually faster: http://jsperf.com/hashcodelordvlad

    ORIGINAL

    if anyone is interested, here is an improved ( faster ) version, which will fail on older browsers who lack the reduce array function.

    hashCode = function(s){
      return s.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0);              
    }
    

    one-liner arrow function version :

    hashCode = s => s.split('').reduce((a,b)=>{a=((a<<5)-a)+b.charCodeAt(0);return a&a},0)
    

提交回复
热议问题