Generate random string/characters in JavaScript

前端 未结 30 1776
闹比i
闹比i 2020-11-21 06:34

I want a 5 character string composed of characters picked randomly from the set [a-zA-Z0-9].

What\'s the best way to do this with JavaScript?

30条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 07:29

    In case anyone is interested in a one-liner (although not formatted as such for your convenience) that allocates the memory at once (but note that for small strings it really does not matter) here is how to do it:

    Array.apply(0, Array(5)).map(function() {
        return (function(charset){
            return charset.charAt(Math.floor(Math.random() * charset.length))
        }('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'));
    }).join('')
    

    You can replace 5 by the length of the string you want. Thanks to @AriyaHidayat in this post for the solution to the map function not working on the sparse array created by Array(5).

提交回复
热议问题