> Done a test (requires Firebug - or Firebug lite (which I presume would
> also work)).
> 
> var foo = ["one", 2, "three", new Date()];
> $.each(foo,
>       function()
>       {
>               if(this === 2) return false;
>               console.log(typeof this);
>       }
> )
> 
> This logs:
> 
> ["o", "n", "e"]
> 2
> ["t", "h", "r", "e", "e"]
> Thu Jan 04 2007 13:09:12 GMT+0000 (GMT Standard Time)
> 
> To the console, rather than just:
> 
> "one"
> 
> typeof(this) within $.each always returns 'object', so identity
> comparison doesn't work (you have to use == instead of ===)

$.each() uses Function.apply() to set "this" for the callback function.
Function.apply() converts its first argument to Object. That's why ===
doesn't work.

> Also, why does a string get returned as an array instead of a string?

It's not being passed as an array, it's being passed as an Object. Firebug
sees that the Object has a .length property and assumes it's an array. If
you use alert() instead of console.log() you'll see something closer to what
you expect.

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.

-Mike


_______________________________________________
jQuery mailing list
[email protected]
http://jquery.com/discuss/

Reply via email to