JavaScript:循环一段时间

JavaScript: loop with a while

本文关键字:一段时间 循环 JavaScript      更新时间:2023-09-26

我在Codecademy学习,现在我面临这样的问题:网站说我"你是否在控制台上记录'我正在循环!'三次?",但我无法克服它。求求你,帮帮我。

有代码:

var loop = function()
{
    var x = 0 ;
while(x)
{
        while(x<3)
        {
            console.log("I'm looping!");
            x+=1;                       
        }
        x+=1;
}
};

您将 x 设置为零,在条件中计算结果为 false。

while(0) 

本质上等于

while(false)

永远不会运行。

将您的代码更改为此代码

var loop = function()
{
    var x = 1;
while(x)
{
    while(x<=3)
    {
        console.log("I'm looping!");
        x+=1;                       
    }
    x-=1;
}
};

你还有一堆不必要的代码。您可以将其缩短为:

while(x<3){
    console.log("I'm looping!");
    x++;
}

或者干脆

for(x=0;x<3;x++){
  console.log("I'm looping");
}

> 现在需要双while循环,实际上,这似乎是for循环的情况,但您可以使用while

var x = 0;
while(x<3)
{
    console.log("I'm looping!");
    x+=1;                       
}

或者使用for循环,因为您知道限制:

for (var x = 0; x < 3; x++) {
    console.log("I'm looping!");
}

这将使用 while 语句打印"我正在记录"三次。

var x = 0;
while (x < 3) {
    console.log("I am logging.");
    x += 1;
}