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


当前回答

我使用@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

其他回答

很好,很简单,而且不局限于一定数量的字符:

let len = 20, str = "";
while(str.length < len) str += Math.random().toString(36).substr(2);
str = str.substr(0, len);
var randomString = function(length) {
  var str = '';
  var chars ='0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split(
      '');
  var charsLen = chars.length;
  if (!length) {
    length = ~~(Math.random() * charsLen);
  }
  for (var i = 0; i < length; i++) {
    str += chars[~~(Math.random() * charsLen)];
  }
  return str;
};

beans建议的另一种答案变体

(Math.random()*1e32).toString(36)

通过改变乘数1e32,你可以改变随机字符串的长度。

32个字符:

for(var c = ''; c.length < 32;) c += Math.random().toString(36).substr(2, 1)

我使用@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