问题
Is it possible for a for-loop to repeat a number 3 times? For instance,
for (i=0;i<=5;i++)
creates this: 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
Is that possible?
回答1:
 for (i=1;i<=5;i++)
     for(j = 1;j<=3;j++)
         print i;
回答2:
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)
回答3:
You can have two variables in the for loop and increase i only when j is a multiple of 3:
for (i=1, j=0; i <= 5; i = ++j % 3 != 0 ? i : i + 1)
回答4:
Definitely. You can nest for loops:
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. I have fixed that to match your description in my answer.
回答5:
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
回答6:
You can use nested for loops
for (var i=0;i<5; i++) {
  for (var j=0; j<3; j++) {
   // output i here
  }
}
回答7:
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);
回答8:
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 );
回答9:
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.
来源:https://stackoverflow.com/questions/5709798/javascript-for-loop-question