Exception handling vs. hasNext()
Yuh-Ruey Chen
maian330 at gmail.com
Mon Nov 19 00:38:13 PST 2007
Garrett Smith wrote:
> How is it possible to iterate over the keys in a Map? I'd like to
> avoid using try/catch, unless something in the loop body might require
> it, and in that case, I'll want to be very clear on what might throw
> an exception, how, and why, as well as provide correct handling of
> that exception. Is there a way to get a maps keys as an Array?
>
I think you're misunderstanding how iterators work. You don't need to
explicitly use the next() method or catch StopIteration. Please look at
how Python does it. There are plenty of examples on the web; here's one:
for x in range(10):
print(x)
which is practically equivalent in ES3 to:
for (let x = 0; x < 10; ++x)
print(x);
The Python for-in is equivalent in ES4 (assuming range is defined
equivalently) to:
for (let x in range(10))
print(x);
This practically translates to:
let $iter = range(10); // $iter not visible to rest of code
try {
for (;;)
{
let x = $iter.next();
print(x);
}
} catch (e: StopException) {}
As you can see, the for-in loop syntax completely hides the next() and
StopIteration. It's definitely not as cumbersome as you think - in fact,
it's even easier to use than hasNext()/next()-style iterators.
To answer your specific question, Map should have a getKeys() method
(according to the wiki) that returns an iterator iterating over the keys
of the map:
for (let k in map.getKeys())
print(k);
FYI, the original ES3 for-in is actual a special case of the ES4 for-in.
When you do |for (let p in obj)|, it's actually iterating over obj's
intrinsic iterator (obj.iterator::get() according to the wiki), which
enumerates obj's properties, just like what it does in ES3.
-Yuh-Ruey Chen
More information about the Es4-discuss
mailing list