您要做的第一件事是创建一个辅助函数,该函数可以从数组中获取随机值。
getRandomValue(array) {
const min = 0; // an integer
const max = array.length; // guaranteed to be an integer
/*
Math.random() will return a random number [0, 1) Notice here that it does not include 1 itself
So basically it is from 0 to .9999999999999999
We multiply this random number by the difference between max and min (max - min). Here our min is always 0.
so now we are basically getting a value from 0 to just less than array.length
BUT we then call Math.floor on this function which returns the given number rounded down to the nearest integer
So Math.floor(Math.random() * (max - min)) returns 0 to array.length - 1
This gives us a random index in the array
*/
const randomIndex = Math.floor(Math.random() * (max - min)) + min;
// then we grab the item that is located at that random index and return it
return array[randomIndex];
}
你可以使用这个辅助函数而不用考虑改变字符串的长度,像这样:
var randomString = getRandomValue(charset) + getRandomValue(charset) + getRandomValue(charset);
但是,您可能希望根据您希望随机字符串的长度创建另一个包含循环的函数:
function getRandomString(charset, length) {
var result = '';
for (var i = 0; i <= length; i++) {
result += getRandomValue(charset);
}
return result;
}
这个函数会这样使用
var randomString = getRandomString(charset, 3);