For a loop with an arithmetic expression

Can arithmetic expressions be used in a for loop?

eg.

<script>
   var i=2;

   for(i=2;i<10;i+2){
      document.write(i);
   }
</script>
+4
source share
2 answers

The problem is not in adding 2in i, but in what is i+2not the destination, so this will lead to an infinite loop. You can write it like this:

var i;
for(i = 2; i < 10; i += 2){
  document.write(i);
}

i += 2means "add 2 to iand save the result in i", basically twice i++.

An example is fixed here .

An example with an infinite loop here

+6
source

With add destination :

. . . . .

for (i = 2; i < 10; i += 2) {
//                    ^^

:

var i =0;
for (i = 2; i < 10; i += 2) {
    document.write(i + '<br>');
}
Hide result
+2

Source: https://habr.com/ru/post/1623802/


All Articles