Generate a Hash from string in Javascript

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

    This generates a consistent hash based on any number of params passed in:

    /**
     * Generates a hash from params passed in
     * @returns {string} hash based on params
     */
    function fastHashParams() {
        var args = Array.prototype.slice.call(arguments).join('|');
        var hash = 0;
        if (args.length == 0) {
            return hash;
        }
        for (var i = 0; i < args.length; i++) {
            var char = args.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash; // Convert to 32bit integer
        }
        return String(hash);
    }
    

    fastHashParams('hello world') outputs "990433808"

    fastHashParams('this',1,'has','lots','of','params',true) outputs "1465480334"

提交回复
热议问题