How is randomness achieved with Math.random in javascript?

后端 未结 5 502
傲寒
傲寒 2020-11-29 11:02

How is randomness achieved with Math.random in javascript? I\'ve made something that picks between around 50 different options randomly. I\'m wondering how comfortable I sho

5条回答
  •  有刺的猬
    2020-11-29 11:31

    Using Math.random() is fine if you're not centrally pooling & using the results, i.e. for OAuth.

    For example, our site used Math.random() to generate random "nonce" strings for use with OAuth. The original JavaScript library did this by choosing a character from a predetermined list using Math.random(): i.e.

    for (var i = 0; i < length; ++i) {
        var rnum = Math.floor(Math.random() * chars.length);
        result += chars.substring(rnum, rnum+1);
    }
    

    The problem is, users were getting duplicate nonce strings (even using a 10 character length - theoretically ~10^18 combinations), usually within a few seconds of each other. My guess this is due to Math.random() seeding from the timestamp, as one of the other posters mentioned.

提交回复
热议问题