Das erste, was Sie wollen tun, ist eine Hilfsfunktion erstellen, die einen Zufallswert greifen aus einem Array.
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];
}
Sie könnten diese Hilfsfunktion ohne Rücksicht verwenden, um die Länge der Zeichenfolge für die Änderung, wie folgt aus:
var randomString = getRandomValue(charset) + getRandomValue(charset) + getRandomValue(charset);
Sie können jedoch eine andere Funktion erstellen möchten, die eine Schleife enthält, basierend darauf, wie lange wollen Sie die zufällige Zeichenfolge sein:
function getRandomString(charset, length) {
var result = '';
for (var i = 0; i <= length; i++) {
result += getRandomValue(charset);
}
return result;
}
Und würde diese Funktion wie diese
verwendet werden
var randomString = getRandomString(charset, 3);
https://www.npmjs.com/package/randomstring – user93
Es funktioniert für Sie? , @ 3gwebtrain –