【问题标题】:the less than operator in javascript (<) is working as less or equals to [duplicate]javascript (<) 中的小于运算符的工作方式小于或等于 [重复]
【发布时间】:2021-11-05 02:11:24
【问题描述】:

此代码应该使用 while 循环和 if 语句在 javascript 中显示给定名称的随机字符/字母。 . . 我面临的问题是 RandomLetterIndex 介于 0 和 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循环。只需调整您的随机器:const RandomLetterIndex = Math.floor(Math.random() * (MyName.length - 0) + 0); 并简单地记录结果。

标签: javascript if-statement while-loop


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    while (RandomLetterIndex &gt; MyName.length - 1) {

    用负1试试这个。

    【讨论】:

      【解决方案3】:

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

      另外,你打破了循环,因此 while 检查有点没用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-01
        • 2019-12-07
        • 2022-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多