为什么 while 循环以字符串结束,而不以整数结束?

Why does the while loop stop with a string, but not with an integer?

我花了很多时间搜索和调试,但我就是想不通为什么当我的变量是一个字符串时 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 变成一个字符串,但我仍然不明白为什么第二个片段不起作用。)

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

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