[SOLVED] How can I use a for loop to extract a string of characters from an array in .js


This Content is from Stack Overflow. Question asked by C Dub

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++){

to work.

Any help is appreciated.


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();

This Question was asked in StackOverflow by C Dub and Answered by Jannchie It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?