Can I use arithmetic expressions in a for loop?
e.g.
<script>
var i=2;
for(i=2;i<10;i+2){
document.write(i);
}
</script>
The problem is not adding 2
to i
, but that i+2
is not an assignment, so it will result in an infinite loop. You can write it like this:
var i;
for(i = 2; i < 10; i += 2){
document.write(i);
}
i += 2
means "add 2 to i
and store the result in i
", basically twice i++
.
Example fixed here.
Example with infinite loop here
With addition assignment:
The addition assignment operator adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator. Addition or concatenation is possible. See the addition operator for more details.
for (i = 2; i < 10; i += 2) {
// ^^
Example:
var i =0;
for (i = 2; i < 10; i += 2) {
document.write(i + '<br>');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With