Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 676
user713052 Avatar asked Dec 07 '25 10:12

user713052


2 Answers

 for (i=1;i<=5;i++)
     for(j = 1;j<=3;j++)
         print i;
like image 78
Vincent Ramdhanie Avatar answered Dec 10 '25 05:12

Vincent Ramdhanie


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)

like image 34
yan Avatar answered Dec 10 '25 05:12

yan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!