Link to home
Start Free TrialLog in
Avatar of Allen Pitts
Allen PittsFlag for United States of America

asked on

Javascript Index Array Variable

Hello expert,

Thanks to COBOL Dinasaur for helping me to get the JavaScript to work.
Code attached.

These are statements I believe to be true. Correction or comments
solicited.

In the line right after the array is listed is the statement "i=0;". Was not sure
what this was for. So I removed it and the script broke. I thought it was defining
the variable i. So it tried   "var i=0;" and it still worked. So my surmise is "i=0;" defines the index variable i and sets it to zero.
So I tried "i=2; and the screen started red and then went to yellow.
So the line
 i=(i>=colors.length) ? 0 : i+1;
is taking the array index number and incrementing it. It starts with zero (red),
then takes the index variable i, which is set to two (green)  and kicks it up a
notch to three (yellow). Thats why with i set to two the screen goes red, yellow.
Also the reason it always starts with red is the script is set to do that with
document.body.style.backgroundColor = colors[0];
This was proved by changing the array number from zero to two which makes the screen
begin green.

Question

I thought that the script would loop thru the colors and stop. The reason
it does not stop is the conditional statement    
 i= (i>=colors.length) ? 0 : i+1;
says if the index var (i) is greater than the length of the array then
set the index var back to zero If the index var is not greater
than the length of the array then increment the index var.

Actually I think I just proved this is true. If the conditional is
removed and  
i= (i>=colors.length) ? 0 : i+1;
is substituted with
i = i+1
then the screen starts with red loops thru the colors and stops with
purple.

Ok. So I answered my own question. Often it is by thinking about
a system long enough to ask a logical question that the answer
is discovered. If you have any comments I am still interested.

Thanks again.

Allen in Dallas
change-k.html
ASKER CERTIFIED SOLUTION
Avatar of Pierre Cornelius
Pierre Cornelius
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial