jQuery: The Write Less, Do More JavaScript Library

Changeset 4447

Show
Ignore:
Timestamp:
01/14/08 20:06:34 (6 months ago)
Author:
jeresig
Message:

Added support for breaking in an object loop (Bug #2111).

Location:
trunk/jquery
Files:
2 modified

Legend:

Unmodified
Added
Removed
  • trunk/jquery/src/core.js

    r4444 r4447  
    708708    each: function( object, callback, args ) { 
    709709        if ( args ) { 
    710             if ( object.length == undefined ) 
     710            if ( object.length == undefined ) { 
    711711                for ( var name in object ) 
    712                     callback.apply( object[ name ], args ); 
    713             else 
     712                    if ( callback.apply( object[ name ], args ) === false ) 
     713                        break; 
     714            } else 
    714715                for ( var i = 0, length = object.length; i < length; i++ ) 
    715716                    if ( callback.apply( object[ i ], args ) === false ) 
     
    718719        // A special, fast, case for the most common use of each 
    719720        } else { 
    720             if ( object.length == undefined ) 
     721            if ( object.length == undefined ) { 
    721722                for ( var name in object ) 
    722                     callback.call( object[ name ], name, object[ name ] ); 
    723             else 
     723                    if ( callback.call( object[ name ], name, object[ name ] ) === false ) 
     724                        break; 
     725            } else 
    724726                for ( var i = 0, length = object.length, value = object[0];  
    725727                    i < length && callback.call( value, i, value ) !== false; value = object[++i] ){} 
  • trunk/jquery/test/unit/core.js

    r4441 r4447  
    13151315 
    13161316test("$.each(Object,Function)", function() { 
    1317     expect(8); 
     1317    expect(12); 
    13181318    $.each( [0,1,2], function(i, n){ 
    13191319        ok( i == n, "Check array iteration" ); 
     
    13271327        ok( i == n, "Check object iteration" ); 
    13281328    }); 
     1329 
     1330        var total = 0; 
     1331        jQuery.each([1,2,3], function(i,v){ total += v; }); 
     1332        ok( total == 6, "Looping over an array" ); 
     1333        total = 0; 
     1334        jQuery.each([1,2,3], function(i,v){ total += v; if ( i == 1 ) return false; }); 
     1335        ok( total == 3, "Looping over an array, with break" ); 
     1336        total = 0; 
     1337        jQuery.each({"a":1,"b":2,"c":3}, function(i,v){ total += v; }); 
     1338        ok( total == 6, "Looping over an object" ); 
     1339        total = 0; 
     1340        jQuery.each({"a":3,"b":3,"c":3}, function(i,v){ total += v; return false; }); 
     1341        ok( total == 3, "Looping over an object, with break" ); 
    13291342}); 
    13301343