Bug Tracker

Opened 14 years ago

Closed 13 years ago

#3877 closed enhancement (wontfix)

$.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:


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_ = [];
               var val = this[prop];
               var target =
                       val === null ? null_ :
                       val === undefined ? undefined_ :
                       (col[val] = col[val] || []);
       $.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.

Change History (6)

comment:1 Changed 14 years ago by dmethvin

Resolution: invalid
Status: newclosed


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.

comment:2 Changed 14 years ago by john

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.

comment:3 Changed 14 years ago by dmethvin

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 );

comment:4 Changed 14 years ago by StaticShock

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:


comment:5 Changed 14 years ago by brandon

Milestone: 1.3.1

comment:6 Changed 13 years ago by john

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.

Note: See TracTickets for help on using tickets.