如何终止浏览器中JavaScript无限循环?年龄校验程序循环异常排查
解决JavaScript无限循环问题及代码修复
一、终止浏览器中的无限循环
- 打开浏览器开发者工具(快捷键:Chrome/Firefox按
F12或Ctrl+Shift+I,Edge按F12) - 切换到「Sources」(Chrome)或「调试器」(Firefox)面板,点击暂停按钮(⏸️)即可中断脚本执行
- 紧急情况下直接关闭当前标签页也能终止循环
二、代码问题分析与修复
你的循环无法终止的核心原因是:循环内部没有更新runagain变量的值。一旦runagain被设为true,循环条件永远为真,陷入无限循环。
修复后的完整代码
//→ Write a program using prompt function to take input of age as a value from the user and use alert to tell him if he can drive let age = prompt("Please enter your age:"); age = parseInt(age); // Convert the input to a number function check(age) { // 简化条件,同时修正拼写错误 if (age >= 0 && age <= 90 && age >= 16) { alert("You can drive!"); } else { alert("Sorry, you cannot drive or the number is not valid"); } } check(age); let runagain = confirm("Do you want to continue?"); while (runagain === true) { let b = prompt("Enter the age"); b = parseInt(b); check(b); // 关键:在循环内部重新询问是否继续,更新runagain的值 runagain = confirm("Do you want to continue?"); }
关键修改点
- 在
while循环末尾添加runagain = confirm("Do you want to continue?");,每次循环结束后重新确认用户意愿,以此更新循环条件 - 修正提示文本拼写错误:
canot→cannot,vaild→valid - 调整
check函数的条件顺序,先判断年龄范围合法性,再判断是否达到驾驶年龄,逻辑更清晰
内容的提问来源于stack exchange,提问作者Sudip Sharma
相关产品推荐
相关产品推荐

