javascript - (JavaScript) 为什么 while 循环中的“if”中的 continue 语句会使浏览器崩溃?
问题描述
我想用 JavaScript 编写一个程序来打印除 5 和 10 之外的从 1 到 20 的所有数字。当我使用这样的 for 循环时:
for (x = 1; x <= 20; x++) {
if (x == 5 || x == 10) {
continue;
}
document.write(x + ' ');
}
它工作正常并打印1 2 3 4 6 7 8 9 11 12 13 14 15 16 17 18 19 20
。
但是,当我尝试使用这样的 while 循环时:
var x = 1;
while (x <= 20) {
if (x == 5 || x == 10) {
continue;
}
document.write(x + ' ');
x++;
}
它使网页无响应,我收到提示,要求我关闭它。这里有什么问题?
解决方案
问题如下,在for 循环中continue将跳回更新表达式x++但在 while 循环中它将跳回运行条件while(x <= 20)
参考mdn 文档。
在 while 循环中,它跳回到条件。在 for 循环中,它跳转到更新表达式。
因为您没有更新条件内的计数器
while (x <= 20) {
if (x == 5 || x == 10) {
continue;
}
x 将保持 5 并且永远不会更新,因为在 while 循环内继续它会跳回运行条件。这将陷入无限循环。
要解决它,您可以在while 循环内的 continue 语句之前增加计数器
while (x <= 20) {
if (x == 5 || x == 10) {
x++
continue;
// for (x = 1; x <= 20; x++) {
// if (x == 5 || x == 10) {
// continue;
// }
// document.write(x + ' ');
//}
var x = 1;
while (x <= 20) {
if (x == 5 || x == 10) {
x++
continue;
}
document.write(x + ' ');
x++;
}
推荐阅读
- sql - Stripe Sigma 查询返回已完成交易的汇率
- javascript - TypeError 无法读取 TypeScript、NextJS 项目上未定义的属性“cwd”
- python - python mac/windows计算问题
- typescript - 打字稿:除非使用关键字“as”,否则传播运算符不起作用
- c# - 我可以依赖为较旧的 .NET 标准构建的项目吗?
- pnpm - 为什么 pnpm 在顶层链接某些依赖项?
- java - 如何将值从活动传递到 Android Studio 中的类?
- linux - 在 Linux 上为远程存储库(Bitbucket)的 git pull 自动输入用户名和密码?
- python - 根据没有 for 循环的条件更新数据帧值
- c# - NET Standard 库可以引用另一个 NET Standard 库吗?