From: Jorge on
Is it possible ?

--
Jorge.
From: Richard Cornford on
On Mar 4, 2:14 pm, Jorge wrote:
> Is it possible ?

Possible? It is almost inevitable.

Richard.
From: Stevo on
Jorge wrote:
> Is it possible ?
>
> --
> Jorge.

Does break; not work ?
From: kangax on
On 3/4/10 9:14 AM, Jorge wrote:
> Is it possible ?

`throw` will take you out of it. But then you might want a wrapper to
handle it gracefully, and it all adds complexity of course.

Here's an untested example:

Array.prototype.each = (function(){
var stopIterationError = { };
return function(callback, thisValue) {
try {
this.forEach(function() {
if (callback.apply(thisValue, arguments) === false) {
throw stopIterationError;
}
});
}
catch(err) {
if (err !== stopIterationError) {
throw err;
}
}
};
})();

[1,2,3].each(function(item, index){
console.log(arguments);
if (index == 1) return false;
});

(Maybe you can replace that `stopIterationError` object with an object
that inherits from `Error`; I'm not sure how cross-browser it would be)

--
kangax
From: Stefan Weiss on
On 04/03/10 15:14, Jorge wrote:
> Is it possible ?

AFAIK, it isn't. With iterators, you could at least throw a
StopIteration, but I don't see any possibility with forEach().

You could try using something along the lines of:

function walk (list, fun, context) {
var i = 0,
len = list.length,
rv;
for (; i < len; i++) {
if (i in list) {
rv = fun.call(context, list[i], i);
if (rv !== undefined) {
return rv;
}
}
}
}

This works similar to Array.prototype.forEach, but will stop looping if
the function "fun" returns anything other than undefined. It can also
double as a filter to find the first array element matching your
criteria. Adding this to Array.prototype is straight-forward, but if
it's stand-alone, you can use it to iterate over node lists (for
example) as well as arrays.

--
stefan