No you can't. i in your scenario is the key for each value so the only way to get the actual value would to do ['val1', 'val2', 'val3'][i] which would defeat the purpose :)
ShawnCplus
Code Monkey
1,583 posts since Apr 2005
Reputation Points: 526
Solved Threads: 268
Is it possible to iterate through an anonymous array of strings with a for loop?
Here's what I'm trying to do:
for ( i in ['country', 'city', 'state'] ) {
doSomethingWithString(i);
}
What I want is the string, but what I'm getting is the index number of the array, which I can't use because the array isn't named.
Thank you.
--
-- Ghodmode
in fact, there is no such thing as anonymous array, this supposedly "arrray" will be garbage collected as soon as the function has passed over.
Therefore you must initiate/create that array before using it at least locally.
for ( i in o = ['country', 'city', 'state'] ){
doSomethingWithString(o[i]);
}
A more readable written form of the same with array value alert:
for ( value in option = ['country', 'city', 'state'] ){
alert( option[ value ] )
}
will serially alert:
country
city
state --- I believe this was what you were looking for.
Cheers.
Troy III
Practically a Master Poster
609 posts since Jun 2008
Reputation Points: 120
Solved Threads: 80
It should be noted, however, that you can hack around it by not using an array but using an object like so
for ( i in ['key1', 'key2'])
alert(i); // 1, and 2 respectively
// BUT
for ( i in {key1:0, key2:0})
alert(i); // key1, and key2 respectively
ShawnCplus
Code Monkey
1,583 posts since Apr 2005
Reputation Points: 526
Solved Threads: 268
Thanks to both ShawnCplus and Troy III. Troy's solution is what I was looking for, but using the object notation as Shawn did is an idea with potential, too.
I guess I used the wrong term when I called it an "anonymous array", but I'm glad you got the idea. I was talking about iterating through a list of strings that could be thrown away as soon as I was done going through the list.
This is the first time I've read the term "garbage collection" in the context of JavaScript. I usually only read it in reference to Java, where the process is incredibly well documented. If I think of the browser as the JavaScript equivalent of Java's "virtual machine", is it basically the same process?
Thank you.
--
-- Ghodmode
No,
it is even better!
:')
That's why you never heard of it before.
This one is automatic and doesn't need coders assistance. There are very rare situations when a coder might begin to notice its leaks or his own misuse of objects and vars etc.
Troy III
Practically a Master Poster
609 posts since Jun 2008
Reputation Points: 120
Solved Threads: 80