+ 3

Why j have a 4 value?

function count() { var i, j; // for (i = 0; i < 3; i++) { j = i * 2; } alert( i ); // i=3 alert( j ); // j=4 }

29th Apr 2017, 9:56 AM
Kristina Hakobyan
Kristina Hakobyan - avatar
7 Respostas
+ 5
that "for" loop work in first time j = 0*2 in seond time j = 1*2 The last time (thirth) j = 2*2 At last "j = 4"
29th Apr 2017, 10:00 AM
Yanothai Chaitawat
Yanothai Chaitawat - avatar
+ 4
Yep so many people why i = 3 look at this for(i=0;i<3;i++) In second condition is false so loop is stop but that loop execute i++ along too (in thirth time) So i=3 at last
29th Apr 2017, 10:03 AM
Yanothai Chaitawat
Yanothai Chaitawat - avatar
+ 4
If you have a loop like this: for (i=0;i<3;i+=0.4) { /* do something if i<3 */ } alert(i); ... the variable 'i' will have successively the values 0, 0.4, 0.8, 1.2, 1.6, 2, 2.4, 2.8, 3.2: at first value of not i<3 ( here 3.2 ) the loop break BEFORE executing its body instruction, so last value of 'i' really used by the loop instructions is 2.8 but last value assigned to it is 3.2 ;)
29th Apr 2017, 10:22 AM
visph
visph - avatar
+ 3
but I last value 3
29th Apr 2017, 10:00 AM
Kristina Hakobyan
Kristina Hakobyan - avatar
+ 3
but why I =3
29th Apr 2017, 10:01 AM
Kristina Hakobyan
Kristina Hakobyan - avatar
+ 3
when I =3 loop will be stop yes I understand right and totally have a 3 value loop always working so
29th Apr 2017, 10:05 AM
Kristina Hakobyan
Kristina Hakobyan - avatar
+ 3
thx guys very much I understand all
29th Apr 2017, 10:24 AM
Kristina Hakobyan
Kristina Hakobyan - avatar