0

I need to create loop number but with increment 0.5

for(var i = 1; i <= 10; i < i++){
  var newOption = $('<option value="'+i+'">'+i+' Minute</option>');
  $('.duration').append(newOption);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="duration"></select>

What I expected is like this:

1
1.5
2
2.5
3
3.5

So on until 10

Any idea how to do the trick?

Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42
HiDayurie Dave
  • 1,791
  • 2
  • 17
  • 45
  • Why are do you have `i <` before `i++`? That part of the for loop isn't a condition, it's just code to execute after each iteration. – Barmar Sep 08 '21 at 04:07

2 Answers2

2

Just use i+= 0.5 like this:

for(var i = 1; i <= 10; i+= 0.5){
  var newOption = $('<option value="'+i+'">'+i+' Minute</option>');
  $('.duration').append(newOption);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="duration"></select>
Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42
1

Just use i+= 0.5 in the last part of loop.

for(var i = 1; i <= 10; i+= 0.5) {
 console.log(i)
}

A for loop has 3 parts:

for ([initialExpression]; [conditionExpression]; [incrementExpression])
 statement

When a for loop executes, the following occurs:

  • The initializing expression initialExpression, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity. This expression can also declare variables.
  • The conditionExpression expression is evaluated. If the value of conditionExpression is true, the loop statements execute. If the value of condition is false, the for loop terminates. (If the condition expression is omitted entirely, the condition is assumed to be true.) The statement executes. To execute multiple statements, use a block statement ({ ... }) to group those statements.
  • If present, the update expression incrementExpression is executed. Control returns to Step 2.

So you can set any incrementExpression you want, like += 0.5 or anything else.

Loops and iteration

Saeed
  • 5,413
  • 3
  • 26
  • 40