Pick a random letter from string in JavaScript

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

    While those above are nice. I like shorter code.

    const randomLetter = ('abcdefghijklmnopqrstuvwxyz').split('')[(Math.floor(Math.random() * 26 ))];
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-03 11:27

    Because you should obtain the letter every time, but you do it just once.

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

    Also, not sure what you wanted to achieve with emptyString++, removing that, since ++ is the "increment by one" operator and you can't incremenent a string. I think the purpose was to have it as a counter for that while loop, but it's needless, since the counter is the string length already.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题