why does counter not stop?

B

bob

Hi,

Question about For (...).
I did this:
for (i=1;i=5;i++)
alert(i)

and i get an infinite loop with value '5'. I thought that 'i=5' was the test
which must be 'true' in order to execute 'alert(i)'. It's normal that i
don't get 1 to 4 because in those case, the test is false. When i=5, i get
alert(i) with 5 but appearantely, i never equals 6.

By the way, is there a difference between i++ and ++i? I tried both but
didn't find any difference.

Thanks
bob
 
D

David Dorward

bob said:
Question about For (...).
I did this:
for (i=1;i=5;i++)
alert(i)

and i get an infinite loop with value '5'. I thought that 'i=5' was the
test which must be 'true' in order to execute 'alert(i)'.

Two problems:

(1) The second parameter of the for loop has to be true to keep looping. It
will execute the content of block every time it loops.

(2) "=" is the assignment operator. The numerical test operator is "==".
It's normal that i don't get 1 to 4 because in those case

Nope. The first time round the loop you set i to 1, and then immediately
afterwards you set it to 5.
, the test is false.

i=5 is always true
When i=5, i get alert(i) with 5 but appearantely, i never equals 6.

Becuase you add one to it, and then set it back to 5 again.
By the way, is there a difference between i++ and ++i? I tried both but
didn't find any difference.

It's a case of when the increment happens.

<script type="text/javascript">
i = 0;
document.write (i +'<br>'+ i++ +'<br>'+ i +'<br>'+ ++i +'<br>'+ i);
</script>

might make things clear if you follow it through carefully.
 
B

bob

thanks for replying


David Dorward said:
Two problems:

(1) The second parameter of the for loop has to be true to keep looping. It
will execute the content of block every time it loops.

(2) "=" is the assignment operator. The numerical test operator is "==".


Nope. The first time round the loop you set i to 1, and then immediately
afterwards you set it to 5.


i=5 is always true


Becuase you add one to it, and then set it back to 5 again.


It's a case of when the increment happens.

<script type="text/javascript">
i = 0;
document.write (i +'<br>'+ i++ +'<br>'+ i +'<br>'+ ++i +'<br>'+ i);
</script>

might make things clear if you follow it through carefully.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top