JS中如何检测prompt输入是否为NaN?解决无限循环异常问题
问题分析与修复方案
嘿,我来帮你搞定这两个头疼的问题——无限循环和NaN的类型困惑,咱们一步步来拆解~
问题1:无限循环的核心原因
你在while循环里重新用let usersAge声明了变量,这会生成一个局部变量,和循环外的usersAge完全是两个独立的家伙!不管你在循环里输入多少次正确数字,外部的usersAge始终是第一次转换失败后的NaN,循环条件Number.isNaN(usersAge)永远为true,自然就停不下来了。
问题2:typeof显示number但值是NaN
这是JavaScript的小特性:NaN(非数字)的类型本身就是number,typeof没法区分它和正常数字,所以得用Number.isNaN()才能准确判断是否是无效数字。
修复后的完整代码
alert("Hi this site is only accessible by people above an age of 18") let usersAge = prompt("How old are you?"); usersAge = Number(usersAge); // 修复循环:不再重新声明变量,直接赋值并转换类型 while (Number.isNaN(usersAge)) { usersAge = Number(prompt("Type in the correct value (a number)?")); } if (usersAge >= 18) { let userName = prompt("Cool, what is your name?"); // 用模板字符串替换拼接,代码更清爽 console.log(`Wassup ${userName} with age of ${usersAge}`); } else { console.log("Sorry your age is too low for us to display this website"); }; console.log(typeof usersAge); console.log(usersAge);
额外优化小细节
- 把字符串拼接改成模板字符串(用反引号
`包裹),可读性直接拉满 - 修正了几个拼写小错误(
accsesable→accessible,pepole→people,ur→your) - 循环提示信息更明确,告诉用户需要输入数字
为啥之前会触发else分支?
因为NaN >= 18的结果是false,哪怕你后来输入了正确年龄,但循环没修改外部的usersAge,它还是NaN,自然就走到了“年龄不够”的分支~
内容的提问来源于stack exchange,提问作者Kandrei
相关产品推荐
相关产品推荐

