首页 > 解决方案 > (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++;
}

它使网页无响应,我收到提示,要求我关闭它。这里有什么问题?

标签: javascripthtmlfor-loopwhile-loop

解决方案


问题如下,在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++;
}


推荐阅读