Skip to main content

Bug Tracker

Side navigation

#3877 closed enhancement (wontfix)

Opened January 15, 2009 04:21PM UTC

Closed December 05, 2009 02:25AM UTC

$.each should return the value returned by the callback

Reported by: StaticShock Owned by:
Priority: minor Milestone: 1.4
Component: core Version: 1.4a1
Keywords: Cc:
Blocked by: Blocking:
Description

It feels more natural if the return value of $.each would be the value returned from the callback. I wrote the following plugin, running into a dead end as soon as i realized that i don't have the callback's return value:

$.fn.eachgroup = function(prop, cb)
{
       var col = {}, null_ = [], undefined_ = [];
       this.each(function()
       {
               var val = this[prop];
               var target =
                       val === null ? null_ :
                       val === undefined ? undefined_ :
                       (col[val] = col[val] || []);
               target.push(this);
       });
       $.each(col, cb);
       // these two should not execute if cb ever returns 'false'
       if (null_.length) cb(null, null_);
       if (undefined_.length) cb(undefined, undefined_);
       return this;
};

I mentioned this on the mailing list, and got no feedback.

Attachments (0)
Change History (6)

Changed January 15, 2009 05:55PM UTC by dmethvin comment:1

resolution: → invalid
status: newclosed

http://docs.jquery.com/Utilities/jQuery.each

Since jQuery.each has been documented to return the object for some time, it would break the interface to change that. Just replace your $.each with a loop.

Changed January 15, 2009 08:14PM UTC by john comment:2

resolution: invalid
status: closedreopened

We had discussed this on the jquery-dev mailing list and agreed that it would be good to look in to. Right now $.each() doesn't return anything in particular.

Changed January 15, 2009 08:34PM UTC by dmethvin comment:3

Sorry, I missed this thread.

http://groups.google.com/group/jquery-dev/browse_frm/thread/91072be7da487e26

I'd definitely advise caution in changing the jQuery.each return value though; it has been documented to return its object argument for some time, and existing code may depend on that. For example, jQuery 1.3 currently implements $().each() like this:

each: function( callback, args ) {
  return jQuery.each( this, callback, args );
},

Changed January 15, 2009 08:39PM UTC by StaticShock comment:4

A good value to return might be "true" if the loop finished and "false" if the loop was interrupted. this would allow the $.each to be used for functionality similar to python's for-else loop:

http://docs.python.org/reference/compound_stmts.html#for

Changed May 04, 2009 02:37AM UTC by brandon comment:5

milestone: 1.3.1

Changed December 05, 2009 02:25AM UTC by john comment:6

milestone: → 1.4
resolution: → wontfix
status: reopenedclosed
version: 1.31.4a1

Yeah, good point from dmethvin. I don't think this is something that we can easily change.