简体   繁体   中英

JavaScript for-loop question

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?

 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)

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)

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.

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 (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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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