在while循环中的continue语句之前使用增量运算符有什么区别? JavaScript

问题描述

我正在尝试编写有关在while循环中使用“ continue”语句的教程的代码。在本教程中,代码编写如下,并且工作正常。

            ...var x = 1;
            document.write("Entering loop");

            while (x < 20) {
                x++;
                if (x == 5) {
                    continue;
                }
                
                document.write(x + "<br />");
            }
            document.write("Exiting the loop");...

但是我尝试了不同的方法,当我将增量语句放在“ if”块之后时,它导致了无限循环,如下所示。

                ...
                var x = 1;
                document.write("Entering loop");
    
                while (x < 20) {
                    
                    if (x == 5) {
                        continue;
                    }
                    x++;
                    document.write(x + "<br />");
                }
                document.write("Exiting the loop");
               ...

我试图绕过它,但是我无法弄清楚。为什么会这样?

解决方法

The

                if (x == 5) {
                    continue;
                }

单独意味着x永远不会改变,直到达到5。x++放在那之前意味着x将会改变。

使用x ++之后,每次都会无限循环continue