如何使console.log计数从1到32?

时间:2014-10-28 16:07:33

标签: javascript

所以我在想像

这样的东西
number = 1;
maxnum = 32;
cat = true;

if (cat == true){
number + 1;
}

沿着这些方向的东西,但我不知道如何实现这一点,使数字从1到32不断变化;在console.log。

5 个答案:

答案 0 :(得分:1)

maxnum = 32;

for(var i=0; i<maxnum; i++}{
console.log(i);
}

答案 1 :(得分:1)

使用此:

   var num = 1;
   var maxnum = 32;
   for(var i = num; i <= maxnum; i++){
      console.log(i);
    }

在for循环中使用变量i作为计数器。通过循环的每一轮,&#39; i&#39;将增加一个。 CodeAcademy将为您提供有关for循环的一些良好实践和基本信息。 Eloquent Javascript用于深入研究javascript语言。

答案 2 :(得分:0)

您可以使用'for'循环:

var maxnum = 32;

for (var i=1; i<maxnum; ++i) {
  console.log(i);
}

答案 3 :(得分:0)

var i = 1,
    maxnum = 32;

while (i <= maxnum){
    console.log(i++);
}

答案 4 :(得分:0)

你需要在你的答案中使用一个循环,一个for循环或一个while循环。

例如,如果将if语句更改为while循环,则可以执行以下操作。

number = 1;
maxnum = 32;
cat = true;

// Change "if" to "while" to make it a loop
while (cat == true){
    // Add the following line to print:
    console.log(number);

    // Update the "cat" variable:
    cat = (number < 32);

    // Make sure this line uses assignment:
    number += 1;
}

然而,for循环是一个更清洁的解决方案。有关如何使用for循环的示例,请参阅此处发布的其他答案。