我想询问用户一个数字,而他的回答不是数字,问题将继续循环(作为一个警告框)。
我尝试使用 while 循环和 isNaN
来做到这一点,但我做错了。
这是我的 Js:
var correct = false;
do {
var question = prompt("guess the number?");
if (question !== isNaN) {
document.write("your number is " + question);
correct = true;
break;
}
} while(! correct);
最佳答案
几个错误
isNaN()
是一个函数:isNaN(NaN)
返回true
而isNaN( 1)
或isNaN("1")
返回false
prompt()
总是返回一个字符串(从不返回NaN
)
您可以使用 unary +
operator 将 prompt() 的结果转换为数字, 然后检查它是否为 NaN
;
var question = prompt("guess the number?");
if (!isNaN(+question)) {
...
也就是说,isNaN()
不适合您只是想查看字符串是否仅包含数字,因为空格(""
或 ""
或 "\n\t"
) 都将转换为 0
并给您误报。
A simple regex会做正确的事;
var question = prompt("guess the number?");
var containsOnlyDigits = /^[0-9]+$/; // one or more of digits 0 to 9
if (containsOnlyDigits.test(question)) {
...
关于JavaScript - 当输入不是数字时提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36552735/