我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。

用JavaScript实现这一点的最佳方法是什么?


当前回答

这是Coffeescapet版本的一行代码

genRandomString = (length,set) -> [0...length].map( -> set.charAt Math.floor(Math.random() * set.length)).join('')

用法:

genRandomString 5, 'ABCDEFTGHIJKLMNOPQRSTUVWXYZ'

输出:

'FHOOV' # random string of length 5 in possible set A~Z

其他回答

npm模块anyid提供了灵活的API来生成各种字符串ID/代码。

const id = anyid().encode('Aa0').length(5).random().id();

这样怎么样:Date.now().toString(36)不是很随意,但每次调用它时都很短且非常独特。

你可以使用coderain。这是一个根据给定模式生成随机代码的库。使用#作为大写和小写字符以及数字的占位符:

var cr = new CodeRain("#####");
console.log(cr.next());

还有其他占位符,如A表示大写字母或9表示数字。

可能有用的是,调用.next()将始终为您提供唯一的结果,因此您不必担心重复。

这里是一个生成唯一随机代码列表的演示应用程序。

完全披露:我是《代码雨》的作者。

function randomString (strLength, charSet) {
    var result = [];
    
    strLength = strLength || 5;
    charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    
    while (strLength--) { // (note, fixed typo)
        result.push(charSet.charAt(Math.floor(Math.random() * charSet.length)));
    }
    
    return result.join('');
}

这是最干净的了。它也很快,http://jsperf.com/ay-random-string.

非常简单

function getRandomColor(){
  var color='';
  while(color.length<6){
    color=Math.floor(Math.random()*16777215).toString(16);
  }
  return '#'+color;
}