Pick a random letter from string in JavaScript

前端 未结 4 520
闹比i
闹比i 2021-01-03 10:58

This question is different from Take random letters out from a string because I am not trying to remove anything from the string.

I\'m trying to pick a rand

4条回答
  •  一整个雨季
    2021-01-03 11:22

    You need to change getRandomLetter into a function, and reassign randomLetter inside the loop like this:

    var emptyString = "";
    var alphabet = "abcdefghijklmnopqrstuvwxyz";
    function getRandomLetter() {
      return alphabet[Math.floor(Math.random() * alphabet.length)];
    }
    var randomLetter;
    
    while (emptyString.length < 6) {
      randomLetter = getRandomLetter();
      emptyString += randomLetter;
    } 
    console.log(emptyString);

    You also can't increment emptyString, since it is a string.

提交回复
热议问题