javascript (<) 中的小于运算符的作用是小于或等于

the less than operator in javascript (<) is working as less or equals to

此代码应该使用 while 循环和 if 语句在 javascript 中显示给定名称的随机字符/字母。 . . 我遇到的问题是 RandomLetterIndex 介于 0 和 5 (<=5) 之间,而我希望它介于 0 和 4 (<5)

之间

const MyName = "Ayman";
var RandomLetterIndex = Math.floor(Math.random() * 10);

while (RandomLetterIndex > MyName.length) {
  RandomLetterIndex = Math.floor(Math.random() * 10);
  if (RandomLetterIndex < MyName.length && RandomLetterIndex !== 5) {
    break
  }
}

console.log(RandomLetterIndex);
console.log(MyName.charAt(RandomLetterIndex));

如果你希望随机数小于单词的长度,而不是使用while循环,你可以这样做

var RandomLetterIndex = Math.floor(Math.random()*MyName.length);

乘以长度而不是 10 确保该值始终位于 [0, length-1] 范围内而不是 [0, 10-1]

问题在于基于 0 的索引和长度 属性。 MyName.length 将等于 5,因此 while 循环将停止并且控制台打印出来。

while (RandomLetterIndex > MyName.length - 1) {

像这样用负 1 试试。

当 RandomLetterIndex 为 5 时,您的 while 循环结束。这就是您在控制台中看到 5 的原因。

此外,您正在打破循环,因此 while 检查有点无用。