From c39bd07cc9f408d5680ba565e2a2fe71bbdc64b9 Mon Sep 17 00:00:00 2001 From: John Resig Date: Mon, 14 Jan 2008 20:06:34 +0000 Subject: [PATCH] Added support for breaking in an object loop (Bug #2111). --- src/core.js | 14 ++++++++------ test/unit/core.js | 15 ++++++++++++++- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/core.js b/src/core.js index bba9883f5..8bec2c74f 100644 --- a/src/core.js +++ b/src/core.js @@ -707,20 +707,22 @@ jQuery.extend({ // args is for internal usage only each: function( object, callback, args ) { if ( args ) { - if ( object.length == undefined ) + if ( object.length == undefined ) { for ( var name in object ) - callback.apply( object[ name ], args ); - else + if ( callback.apply( object[ name ], args ) === false ) + break; + } else for ( var i = 0, length = object.length; i < length; i++ ) if ( callback.apply( object[ i ], args ) === false ) break; // A special, fast, case for the most common use of each } else { - if ( object.length == undefined ) + if ( object.length == undefined ) { for ( var name in object ) - callback.call( object[ name ], name, object[ name ] ); - else + if ( callback.call( object[ name ], name, object[ name ] ) === false ) + break; + } else for ( var i = 0, length = object.length, value = object[0]; i < length && callback.call( value, i, value ) !== false; value = object[++i] ){} } diff --git a/test/unit/core.js b/test/unit/core.js index 72130102a..b2cf8f137 100644 --- a/test/unit/core.js +++ b/test/unit/core.js @@ -1314,7 +1314,7 @@ test("text(String)", function() { }); test("$.each(Object,Function)", function() { - expect(8); + expect(12); $.each( [0,1,2], function(i, n){ ok( i == n, "Check array iteration" ); }); @@ -1326,6 +1326,19 @@ test("$.each(Object,Function)", function() { $.each( { name: "name", lang: "lang" }, function(i, n){ ok( i == n, "Check object iteration" ); }); + + var total = 0; + jQuery.each([1,2,3], function(i,v){ total += v; }); + ok( total == 6, "Looping over an array" ); + total = 0; + jQuery.each([1,2,3], function(i,v){ total += v; if ( i == 1 ) return false; }); + ok( total == 3, "Looping over an array, with break" ); + total = 0; + jQuery.each({"a":1,"b":2,"c":3}, function(i,v){ total += v; }); + ok( total == 6, "Looping over an object" ); + total = 0; + jQuery.each({"a":3,"b":3,"c":3}, function(i,v){ total += v; return false; }); + ok( total == 3, "Looping over an object, with break" ); }); test("$.prop", function() { -- 2.39.5