Link to home
Start Free TrialLog in
Avatar of ShanghaiD
ShanghaiDFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Curious result looping through array

This may be obvious to the experts, but not to me as I am still "learning" javascript.

When I execute this code:
<script type='text/javascript'>
Seasons1 = ["Winter", "Spring", "Summer", "Autumn"];
Seasons2 = ("Winter", "Spring", "Summer", "Autumn");
for (i in Seasons1) {
  document.write(Seasons1[i]);
  document.write('<br />');
}
for (i in Seasons2) {
  document.write(Seasons2[i]);
  document.write('<br />');
}
</script>

Open in new window

I get:
Winter
Spring
Summer
Autumn
A
u
t
u
m
n

Open in new window

What's going on with "Seasons2", and why?
Avatar of basicinstinct
basicinstinct
Flag of Australia image

your syntax is incorrect - the parentheses will execute the statements inside, the result evaluating those statements is being stored in seasons2.

whatever you are trying to do you are not doing it right.
perhaps you mean to do this:

Seasons2 = {0:"Winter", "foo":"Spring", "bar":"Summer", 3:"Autumn"};
Avatar of ShanghaiD

ASKER

Thanks.  The [ ] syntax in Seasons1 works as I expect/want it to work -- and your suggested { } sytax also gives the same result.

My question was really aimed at trying to understand/learn what the ( ) sytax in Seasons2 is dong.  It now seems clear that it does NOT create an array (as [ ] and { } do).

the parentheses will execute the statements inside, the result evaluating those statements is being stored in seasons2
Does this mean that in executing/evaluating what is inside the partnthese that Seasons2 is intially set to "Winter", then to "Spring", then to "Summer" and finally to "Autumn"  -- each "overwriting" the other?  (That would make sense to me).

I'm still curious why the output is printed vertically -- how/why does document.write() do this?
ASKER CERTIFIED SOLUTION
Avatar of basicinstinct
basicinstinct
Flag of Australia 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
oops I meant "new String()"
Thank you for this clear explanation.  I'm always happy to improve my knowledge and understanding.  (I also should have picked up on the document.write('<br />') by usign Firebug to inspect the vertical text.  I will remember to do this next time!)