【问题标题】:Why does the while loop stop with a string, but not with an integer? [duplicate]为什么while循环以字符串停止,而不以整数停止? [复制]
【发布时间】:2021-06-15 06:03:03
【问题描述】:

我花了很多时间搜索和调试,但我就是不明白为什么当我的变量是字符串时,while 循环会在“猜测”时停止...

const myName = 'Daniel';

let guess = prompt("Guess my name!");
while (guess !== myName) {
    guess = prompt("That's incorrect. Guess again!");
}
console.log("Congrats! You guessed my name!")

...但不是整数。

const myAge = 28;

let guess = prompt("Guess my age!");
while (guess !== myAge) {
    guess = prompt("That's incorrect. Guess again!");
}
console.log("Congrats! You guessed my age!")

即使我输入了正确的答案,弹出窗口也会不断出现。我做错了什么?

(我知道我可以把 28 变成一个字符串,但我还是不明白为什么第二个 sn-p 不起作用。)

【问题讨论】:

    标签: javascript string while-loop integer


    【解决方案1】:

    因为!== 包含类型检查,而您只是将字符串“28”与整数28 进行比较,这并不相同。将您的值比较更改为!=,将整数转换为字符串 - 所以const myAge = '28';,或者如果您确定要验证整数输入,则使用parseInt() 将用户的输入转换为整数。

    您将从用户输入中获得一个字符串。总是。不是整数。

    【讨论】:

      猜你喜欢
      • 2016-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-19
      • 2016-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多