Is There a Way to Break out of a forEach ?

2,881 views
Skip to first unread message

babbos

unread,
Feb 17, 2010, 3:59:02 PM2/17/10
to Closure Library Discuss
Hello,

is there some way to break out of goog.array.forEach() ?

Thankyou

Nathan Naze

unread,
Feb 18, 2010, 2:37:08 AM2/18/10
to closure-lib...@googlegroups.com
Nope. Use a for loop and the break keyword, or you could use
goog.array.some() -- the first time your function returns true, the
iteration will stop.

Nathan

Erik Arvidsson

unread,
Feb 18, 2010, 3:15:49 AM2/18/10
to closure-lib...@googlegroups.com
You can use an exception to do this.

var stop = Error();

function func(n) {
if (n > 3) {
throw stop;
}
...
}

try {
goog.array.forEach([0, 1, 2, 3, 4, 5], func);
} catch (ex) {
if (ex !== stop) {
throw ex;
}
}

As you can see this is a lot of boiler plate code and if you have an
array it seems simpler to use a for loop. You might also want to take
a look at what goog.iter has to offer. It allows you to write:

goog.iter.forEach([0, 1, 2, 3, 4, 5], function(n) {
if (n > 3) {
throw goog.iter.StopIteration;
}
...
});

--
erik

babbos

unread,
Feb 18, 2010, 10:01:57 AM2/18/10
to Closure Library Discuss
Thankyou,

that was great advice!!

Nathan Naze

unread,
Feb 18, 2010, 11:55:14 AM2/18/10
to closure-lib...@googlegroups.com
> On Feb 18, 10:15 am, Erik Arvidsson <erik.arvids...@gmail.com> wrote:
>> You can use an exception to do this.

Good point. I hadn't considered exception handling.

Nathan

Reply all
Reply to author
Forward
0 new messages