ShanghaiD
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:
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>
I get:Winter
Spring
Summer
Autumn
A
u
t
u
m
n
What's going on with "Seasons2", and why?
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).
I'm still curious why the output is printed vertically -- how/why does document.write() do this?
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 seasons2Does 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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
oops I meant "new String()"
ASKER
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!)
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"};