在JavaScript中从字符串中选择一个随机字母 [英] Pick a random letter from string in JavaScript

查看:51
本文介绍了在JavaScript中从字符串中选择一个随机字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题不同于从字符串中取出随机字母,因为我不是要从字符串中删除任何内容。

I我试图使用Math.floor(Math.random()* string.length)和while循环从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.

我的代码是:

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

问题:
输出相同的字母6次:ex。 pppppp

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

随机字母仅从字符串生成一次,然后重复直到指定的长度。我需要它为每个字母生成随机输出:ex。 pwezjm

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

我还注意到,如果我在字符串上执行第二个不同的while循环,它将生成与第一个循环相同的输出:ex。 pppppp

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?

推荐答案

因为你每次都应该收到这封信,但你只需要一次。

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

另外,不确定你想用 emptyString ++ ,删除它,因为 ++ 是递增一个运算符,你不能增加一个字符串。我认为目的是让它作为while循环的计数器,但它是不必要的,因为计数器已经是字符串长度。

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.

这篇关于在JavaScript中从字符串中选择一个随机字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆