Create a random token in Javascript based on user details

后端 未结 6 905
醉酒成梦
醉酒成梦 2021-02-01 15:38

I want to create a random string (token) which can be used to identify a user whilst avoiding any potential conflicts with any other users\' tokens.

What I was thinking

6条回答
  •  爱一瞬间的悲伤
    2021-02-01 16:10

    I use an approach similar to Kareem's, but with fewer function calls and built-in array operations for a big boost in performance.

    According to a performance test, this method also outperforms the accepted answer by a small margin. Moreover it provides a parameter n to generate any size token length from a white list of acceptable characters. It's flexible and performs well.

    function generateToken(n) {
        var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        var token = '';
        for(var i = 0; i < n; i++) {
            token += chars[Math.floor(Math.random() * chars.length)];
        }
        return token;
    }
    

提交回复
热议问题