Pick a random letter from string in JavaScript

前端 未结 4 537
闹比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:28

    Get the random character in a loop

    In your example, you are obtaining random character from array only once hence there is no way you are going to get another random character in while loop

    Also note that emptyString++ will cause result as NaN as you are trying to post-increment the string

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

    Another tip, alphabet.length could be cached instead of asking for it every time in while

提交回复
热议问题