简体   繁体   English

JavaScript for循环问题

[英]JavaScript for-loop question

Is it possible for a for-loop to repeat a number 3 times? for循环可以重复3次吗? For instance, 例如,

for (i=0;i<=5;i++)

creates this: 1,2,3,4,5. 创造了这个:1,2,3,4,5。 I want to create a loop that does this: 1,1,1,2,2,2,3,3,3,4,4,4,5,5,5 我想创建一个循环来执行此操作:1,1,1,2,2,2,3,3,3,4,4,4,5,5,5

Is that possible? 那可能吗?

 for (i=1;i<=5;i++)
     for(j = 1;j<=3;j++)
         print i;

Yes, just wrap your loop in another one: 是的,只需将你的循环包装在另一个循环中:

for (i = 1; i <= 5; i++) {
   for (lc = 0; lc < 3; lc++) {
      print(i);
  }
}

(Your original code says you want 1-5, but you start at 0. My example starts at 1) (您的原始代码表示您想要1-5,但是从0开始。我的示例从1开始)

You can have two variables in the for loop and increase i only when j is a multiple of 3: 你可以在for循环中有两个变量,只有当j是3的倍数时才增加i:

for (i=1, j=0; i <= 5; i = ++j % 3 != 0 ? i : i + 1) for(i = 1,j = 0; i <= 5; i = ++ j%3!= 0?i:i + 1)

Definitely. 当然。 You can nest for loops: 你可以嵌套for循环:

for (var i = 1; i < 6; ++i) {
    for(var j = 0; j < 3; ++j) {
        print(i);
    }
}

Note that the code in your question will print 0, 1, 2, 3, 4, 5 , not 1, 2, 3, 4, 5 . 请注意,问题中的代码将打印0, 1, 2, 3, 4, 5 ,而不是1, 2, 3, 4, 5 I have fixed that to match your description in my answer. 我已修复此问题以符合我在答案中的说明。

You could use a second variable if you really only wanted one loop, like: 如果你真的只想要一个循环,你可以使用第二个变量,如:

for(var i = 0, j = 0; i <= 5; i = Math.floor(++j / 3)) {
     // whatever
}

Although, depending on the reason you want this, there's probably a better way. 虽然,根据你想要的原因,可能有更好的方法。

Just add a second loop nested in the first: 只需添加嵌套在第一个循环中的第二个循环:

for (i = 0; i <= 5; i++)
    for (j = 0; j < 3; j++)
        // do something with i

You can use nested for loops 您可以使用嵌套for循环

for (var i=0;i<5; i++) {
  for (var j=0; j<3; j++) {
   // output i here
  }
}

You can use two variables in the loop: 您可以在循环中使用两个变量:

for (var i=1, j=0; i<6; j++, i+=j==3?1:0, j%=3) alert(i);

However, it's not so obvious by looking at the code what it does. 但是,通过查看代码它的作用并不是那么明显。 You might be better off simply nesting a loop inside another: 简单地将循环嵌套在另一个循环中可能会更好:

for (var i=1; i<6; i++) for (var j=0; j<3; j++) alert(i);

I see lots of answers with nested loops (obviously the nicest and most understandable solution), and then some answers with one loop and two variables, although surprisingly nobody proposed a single loop and a single variable. 我看到很多嵌套循环的答案(显然是最好和最容易理解的解决方案),然后是一个循环和两个变量的答案,尽管令人惊讶的是没有人提出单循环和单个变量。 So just for the exercise: 所以只是为了练习:

for(var i=0; i<5*3; ++i)
   print( Math.floor(i/3)+1 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM