Ad

Javascript: Loop Add Number

- 1 answer

How to loop like this one in javascript? 11 21 32 43

I have this code already.

for(var i=11; i <= 43; i += 10){
document.write(i+'<br>');
}
Ad

Answer

If you want to add first 10, then 11 and so on, then your loop would look like the one below. But note that it would loop to 44 instead of 43, since you're adding 12 to 32:

j = 10;
for(var i=11; i <= 44; i += j++){
  document.write(i+'<br>');
}

A slight alteration should give you exactly what you described. Instead of having an extra variable 'j', you can just increment i by 10 + something. Something in your case is 0 when i == 11, or 1 if i > 11. This can be written as a single boolean expression, which will be converted to 0 or 1 when evaluated in a calculation. So the snippet below will give you 11, 21, 32, 43.

for (var i = 11; i <= 43; i += (10 + (i>11))) {
  document.write(i + '<br>');
}

In yet another variation you can always add 11, but start i at 10 and add one for the first iteration. This will also give you the weird sequence of 11, 21, 32, 43, but I think the snippet above is a a little more clear.

for (var i = 10; i <= 43; i += 11) {
  document.write((i + (i==10)) + '<br>');
}

Anyway, there is no need to make a fancy loop. You could just as well write a little more code and implement the logic in a way that is readable and understandable. Maybe use an 'if' inside the loop to affect i.

Ad
source: stackoverflow.com
Ad