> Would you like an Array iterator that works the way you'd
> expect? Here is a simple one:
>
> Array.prototype.each = function( yields ) {
> for( var i = 0, n = this.length; i < n; i++ ) {
> if( yields( this[i], i ) === false )
> break;
> }
> };
>
> Then you can code:
>
> [ "one", 2, "three", new Date() ].each( function( value ) {
> if( value === 2 ) return false;
> console.debug( value );
> });
>
> No "this", no monkey business with Object.
>
> If you don't want to extend Array.prototype, you can code a
> similar standalone function. It's really a very simple
> function, so there's no real reason to compromise with one
> that doesn't work the way you want.
Speaking of which, here are standalone functions with test cases for objects
and arrays:
function objectEach( obj, fn ) {
for( var name in obj )
if( fn( obj[name], name ) === false )
break;
}
function arrayEach( ary, fn ) {
for( var i = 0, n = ary.length; i < n; i++ )
if( fn( ary[i], i ) === false )
break;
}
objectEach(
{ a:'ay', b:'bee', c:'see' },
function( value, name ) {
return confirm( name + ': ' + value );
}
);
arrayEach(
[ 'ay', 'bee', 'see' ],
function( value, index ) {
return confirm( index + ': ' + value );
}
);
Click the Cancel button in any of the confirm() message boxes to return
false and stop the iteration.
Why are the callback function arguments in the order ( value, name/index )
instead of the seemingly more intuitive ( name/index, value )? It's because
in the case of an array, you often want only the array values, so you can
code the callback as function( value ) { ... }.
These functions use simple argument passing instead of apply() and "this",
which makes them easier to code and much easier to understand. That also
avoids the problem we saw earlier where "this" in the $.each callback is
converted to an Object, and it means they work in any version of JavaScript.
-Mike
_______________________________________________
jQuery mailing list
[email protected]
http://jquery.com/discuss/