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

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


当前回答

功能性方法。只有在应用程序的其他部分可以利用功能先决条件时,这个答案才实用。表演可能是垃圾,但写起来非常有趣。

//功能先决条件常量U=f=>f(f)常量Y=U(h=>f=>f(x=>h(h)(f)(x)))常量comp=f=>g=>x=>f(g(x))常量foldk=Y(h=>f=>Y=>([x,…xs])=>x===未定义?y:f(y)(x)(y=>h(f)(y))(xs))常量fold=f=>foldk(y=>x=>k=>k(f(y)(x)))常量映射=f=>fold(y=>x=>[…y,f(x)])([])constchar=x=>String.fromCharCode(x)常量concat=x=>y=>y.concat(x)常量concatMap=f=>comp(fold(concat)([]))(map(f))const irand=x=>数学地板(Math.random()*x)常量样本=xs=>xs[irand(xs.length)]//范围:从x到y的范围;[x…y]//编号->编号->[编号]常量范围=Y(f=>r=>x=>Y=>x>y?r:f([…r,x])(x+1)(y)) ([])//srand:从列表或ascii代码范围生成随机字符串//[(范围a)]->编号->[a]常量srand=comp(Y(f=>z=>rs=>x=>x===0?z:f(z+样本(rs))(rs)(x-1))([]))(concatMap(map(char)))//idGenerator:生成指定长度的标识符//数字->字符串常量idGenerator=srand([范围(48)(57),//包括0-9范围(65)(90),//包括A-Z范围(97)(122)//包括a-z])console.log(idGenerator(6))//=>TT688Xconsole.log(idGenerator(10))//=>SzaaUBlpI1console.log(idGenerator(20))//=>eYAaWhsfvLDhIBID1xRh

在我看来,如果不添加神奇的、做太多事情的功能,很难超越idGenerator的清晰度。

稍有改进

// ord : convert char to ascii code
// Char -> Number
const ord = x => x.charCodeAt(0)

// idGenerator : make an identifier of specified length
// Number -> String
const idGenerator = srand ([
  range (ord('0')) (ord('9')),
  range (ord('A')) (ord('Z')),
  range (ord('a')) (ord('z'))
])

玩得开心。让我知道你喜欢/学习什么^_^

其他回答

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

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

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

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

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

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

这里有一些简单的一行。更改新阵列(5)以设置长度。

包括0-9a-z

new Array(5).join().replace(/(.|$)/g, function(){return ((Math.random()*36)|0).toString(36);})

包括0-9a-zA-Z

new Array(5).join().replace(/(.|$)/g, function(){return ((Math.random()*36)|0).toString(36)[Math.random()<.5?"toString":"toUpperCase"]();});

ES6编码(0-9a-z)

Array(5).fill().map(n=>(Math.random()*36|0).toString(36)).join('')

像这样的东西应该有用

function randomString(len, charSet) {
    charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var randomString = '';
    for (var i = 0; i < len; i++) {
        var randomPoz = Math.floor(Math.random() * charSet.length);
        randomString += charSet.substring(randomPoz,randomPoz+1);
    }
    return randomString;
}

使用默认字符集[a-zA-Z0-9]调用或发送您自己的:

var randomValue = randomString(5);

var randomValue = randomString(5, 'PICKCHARSFROMTHISSET');

这不是一个完美的解决方案,但它应该奏效。如果出现任何错误,请增加Uint8Array()构造函数中给定的值。此方法的优点是它使用getRandomValues()方法生成加密的强随机值。

var array=新Uint8Array(20);crypto.getRandomValues(数组);var arrayEncoded=btoa(String.fromCharCode(…array)).split(“”);var arrayFiltered=arrayEncoded.filter(值=>{开关(值){大小写“+”:return false;大小写“/”:return false;case“=”:return false;违约:返回true;}});var password=arrayFiltered.slice(0,5).join('');console.log(密码);

紧凑型

var array=新Uint8Array(20);crypto.getRandomValues(数组);var password=btoa(String.fromCharCode(…array)).split(“”).filter(值=>{回来['+','/','=']includes(value);}).切片(0,5).连接('');console.log(密码);

我已经制作了一个字符串原型,它可以生成一个给定长度的随机字符串。

如果你想要特殊字符,你也可以解密,你可以避免一些。

/**
 * STRING PROTOTYPE RANDOM GENERATOR
 * Used to generate a random string
 * @param {Boolean} specialChars
 * @param {Number} length
 * @param {String} avoidChars
 */
String.prototype.randomGenerator = function (specialChars = false, length = 1, avoidChars = '') {
    let _pattern = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    _pattern += specialChars === true ? '(){}[]+-*/=' : '';
    if (avoidChars && avoidChars.length) {
        for (let char of avoidChars) {
            _pattern = _pattern.replace(char, '');
        }
    }
    let _random = '';
    for (let element of new Array(parseInt(length))) {
        _random += _pattern.charAt(Math.floor(Math.random() * _pattern.length));
    }
    return _random;
};

您可以这样使用:

// Generate password with specialChars which contains 10 chars and avoid iIlL chars
var password = String().randomGenerator(true, 10, 'iIlL');

希望有帮助。