Bug Tracker

Ticket #3877 (closed enhancement: wontfix)

Opened 6 years ago

Last modified 5 years ago

$.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:
Blocking: Blocked by:

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.

Change History

comment:1 Changed 6 years ago by dmethvin

  • Status changed from new to closed
  • Resolution set to invalid

 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.

comment:2 Changed 6 years ago by john

  • Status changed from closed to reopened
  • Resolution invalid deleted

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 6 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 6 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:

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

comment:5 Changed 5 years ago by brandon

  • Milestone 1.3.1 deleted

comment:6 Changed 5 years ago by john

  • Status changed from reopened to closed
  • Version changed from 1.3 to 1.4a1
  • Resolution set to wontfix
  • Milestone set to 1.4

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.