mercredi 27 juillet 2016

Pick a random letter from string in JavaScript

I'm trying to pick a random letter from a string in JavaScript using Math.floor(Math.random()* string.length) and a while loop. It needs to continually add new random letters to this string until a specified length.

My code is:

var emptyString = "";
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var getRandomLetter = alphabet[Math.floor(Math.random() * alphabet.length)];
var randomLetter = getRandomLetter;

while (emptyString.length < 6) {
emptyString += randomLetter;
emptyString ++;
} 
console.log(emptyString);

Problems: The output is the same letter 6 times: ex. pppppp

The random letter is generated from the string only once and then repeated until the specified length. I need it to generate random output for each letter: ex. pwezjm

I also noticed that if I do a second different while loop over the string it will generate the same output as the first loop: ex. pppppp

I thought it would at least generate a different random letter then the first loop but it does not. Why is that?

Thanks!




Aucun commentaire:

Enregistrer un commentaire