I am new to javaScript and having a terrible time with understanding loops. Currently I have a random text generator function. I have gotten it to generate random characters from a string but only one character each time the function is ran. I would like to build a string of 20 random characters from the output of the function.
This is what I have so far:
function passGen() {
let text = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVVWYXZ()!@#$%&*/? -%".split("");
let randomIndex = Math.floor(Math.random() * text.length);
return text[randomIndex];
}
let randomPass = passGen();
I would like to let the function produce the random character and then use a for loop to out put 20 of these random characters in a string.
I can't get
for (let i = 0; i <= 20; i ){
console.log(randomPass)
to work.
Any help is appreciated.
CodePudding user response:
You need to define a string variable and then use a loop to append characters to it, like this:
function passGen () {
const text = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVVWYXZ()!@#$%&*/? -%'.split('')
let res = ''
for (let i = 0; i < 20; i ) {
res = text[Math.floor(Math.random() * text.length)]
}
return res
}
const randomPass = passGen();
CodePudding user response:
You need to specify for yourself what characters you want to support, for example:
function getRandomCharacter(supportedCharacters) {
return supportedCharacters[parseInt(Math.random() * supportedCharacters.length)];
}
function getRandomString(supportedCharacters, length) {
let output = "";
while (length--) output = getRandomCharacter(supportedCharacters);
return output;
}
console.log(getRandomString([
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z',
], 20));
getRandomCharacter
randomizes a characterMath.random()
generates a real number which is greater or equal than 0 but smaller than 1- multiplying
Math.random()
with the number of supported characters scales the value to the interval between [0, length) parseInt
rounds the result down- the result of
parseInt
can be used as an index
getRandomString
generates all the characters using awhile
looplength--
evaluateslength
and then decreases it by 1=
concatenates the resulting character tooutput
return output;
clarifies that the result of the function is the string
- the test sample defines an array (you could do it with a string as well if you want) of the characters you want to support and the length of the string you desire