Generate a Hash from string in Javascript

前端 未结 22 970
不知归路
不知归路 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:29

    Adding this because nobody did yet, and this seems to be asked for and implemented a lot with hashes, but it's always done very poorly...

    This takes a string input, and a maximum number you want the hash to equal, and produces a unique number based on the string input.

    You can use this to produce a unique index into an array of images (If you want to return a specific avatar for a user, chosen at random, but also chosen based on their name, so it will always be assigned to someone with that name).

    You can also use this, of course, to return an index into an array of colors, like for generating unique avatar background colors based on someone's name.

    function hashInt (str, max = 1000) {
        var hash = 0;
        for (var i = 0; i < str.length; i++) {
          hash = ((hash << 5) - hash) + str.charCodeAt(i);
          hash = hash & hash;
        }
        return Math.round(max * Math.abs(hash) / 2147483648);
    }
    

提交回复
热议问题