Generates a random string with the specified length.
- Use
Array.from()to create a new array with the specifiedlength. - Use
Math.random()generate a random floating-point number. - Use
Number.prototype.toString()with aradixvalue of36to convert it to an alphanumeric string. - Use
String.prototype.slice()to remove the integral part and decimal point from each generated number. - Use
Array.prototype.some()to repeat this process as many times as required, up tolength, as it produces a variable-length string each time. - Finally, use
String.prototype.slice()to trim down the generated string if it’s longer than the givenlength.
代码实现
const randomAlphaNumeric = length => {
let s = '';
Array.from({ length }).some(() => {
s += Math.random().toString(36).slice(2);
return s.length >= length;
});
return s.slice(0, length);
};
randomAlphaNumeric(5); // '0afad'
翻译自:https://www.30secondsofcode.org/js/s/random-alphanumeric