在JavaScript中生成一个随机的字母数字(大写,小写和数字)字符串来用作可能唯一的标识符的最短方法是什么?


当前回答

更新: 一行程序解决方案,随机20个字符(字母数字小写):

Array.from(Array(20), () => Math.floor(Math.random() * 36).toString(36)).join('');

或者用lodash更短:

_.times(20, () => _.random(35).toString(36)).join('');

其他回答

使用lodash:

生物多样性功能(length) var chars =“不可能” 瓦尔pwd = _sampleSize (chars,长度正好| | 12)/ lodash v4:用_ sampleSize。 pwd归来加入(“”)。 的 文件写(createRandomString(8)。 <剧本剧本src = " https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js " > < / >

我只是发现了一个非常好的优雅的解决方案:

Math.random().toString(36).slice(2)

这个实现的注意事项:

This will produce a string anywhere between zero and 12 characters long, usually 11 characters, due to the fact that floating point stringification removes trailing zeros. It won't generate capital letters, only lower-case and numbers. Because the randomness comes from Math.random(), the output may be predictable and therefore not necessarily unique. Even assuming an ideal implementation, the output has at most 52 bits of entropy, which means you can expect a duplicate after around 70M strings generated.

我使用@Nimphious优秀的第二种方法,发现偶尔返回的字符串是数字-而不是字母数字。 我使用的解决方案是测试使用!isNaN,并再次使用递归调用该函数。 何苦呢?我使用这个函数来创建对象键,如果所有的键都是字母数字,那么所有的键都可以正常排序,但如果你使用 数字作为键与字母数字(字符串)混合在一起循环遍历对象将产生与原始顺序不同的顺序。

function newRandomString(length, chars) {
  var mask = '';
  if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
  if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  if (chars.indexOf('#') > -1) mask += '0123456789';
  if (chars.indexOf('$') > -1) mask += '0123456789';

  var result = '';
  for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * 
  mask.length)];
  /*    
        we need a string not a number !isNaN(result)) will return true if '1234' or '3E77'
        because if we're looping through object keys (created by newRandomString()) and 
        a number is used and all the other keys are strings then the number will 
        be first even if it was the 2nd or third key in object
  */
  //use recursion to try again
  if(!isNaN(result)){
    console.log('found a number....:'+result);
    return newRandomString(length, chars)
  }else{
    return result;
  }
};

var i=0;
while (i < 1000) {
  var a = newRandomString(4, '#$aA');
  console.log(i+' - '+a);
  //now we're using recursion this won't occur
  if(!isNaN(a)){
    console.log('=============='+i+' - '+a);
  }
  i++;
}

console.log('3E77:'+!isNaN('3E77'));//true
console.log('1234:'+!isNaN('1234'));//true
console.log('ab34:'+!isNaN('ab34'));//false

可以使用lodash uniqueId:

    _.uniqueId([prefix=''])

生成唯一的ID。如果给出了prefix,则ID被追加到它后面。

这个函数应该给出任意长度的随机字符串。

function randString(length) {
    var l = length > 25 ? 25 : length;
    var str = Math.random().toString(36).substr(2, l);
    if(str.length >= length){
        return str;
    }
    return str.concat(this.randString(length - str.length));
}

我用下面的测试成功地测试了它。

function test(){
    for(var x = 0; x < 300000; x++){
        if(randString(x).length != x){
            throw new Error('invalid result for len ' + x);
        }
    }
}

我选择25的原因是,在实践中,从Math.random(). tostring(36)返回的字符串长度。Substr(2,25)的长度为25。这个数字可以根据您的意愿更改。

此函数是递归的,因此使用非常大的值调用函数可能会导致超过最大调用堆栈大小。从我的测试中,我能够得到长度为30万字符的字符串。

通过将字符串作为第二个参数发送给函数,可以将该函数转换为尾递归。我不确定JS是否使用Tail调用优化