Bug Tracker

Opened 9 years ago

Closed 9 years ago

Last modified 8 years ago

#8547 closed bug (wontfix)

$.each behaviour with null object

Reported by: theaspect@… Owned by:
Priority: undecided Milestone: 1.next
Component: core Version: 1.5.1
Keywords: Cc:
Blocked by: Blocking:

Description

Hi guys? i've posted it on forum, but nobody care, copy bug here why behaviour of

$.each(null,function(){alert(1)})

differs from

for(a in null){alert(1)}

jquery raises exception

TypeError: object is null

So

each: function( object, callback, args ) {
 var name, i = 0,
 length = object.length, <<-HERE COMES PROBLEM
 isObj = length === undefined || jQuery.isFunction(object);

we should test is object is null

Change History (8)

comment:1 Changed 9 years ago by boushley

For in is meant for iterating over members of an object, $.each is meant to iterate over items of an array, so I'm not sure why the comparison is valid. Sure you can use a for in to iterate over an array, but that's because of the way javascript represents arrays.

I don't think this is something we should really be concerned with. Would you propose a null check and then immediately return if it is null? I think this fits under garbage in garbage out.

comment:2 Changed 9 years ago by theaspect@…

@boushley you want me to post the patch?

each: function( object, callback, args ) {

+ if (object == null) return null;

var name, i = 0,

comment:3 Changed 9 years ago by dmethvin

If the code can't help itself but pass null/undefined then just guard against it with $.each(obj||[],function(){alert(1)}) and all is well. That way we don't mask problems and devs can either explicitly say they don't mind null (as above) or figure out why they are getting it in the first place.

comment:4 Changed 9 years ago by theaspect@…

same for underscore.js

http://jsfiddle.net/BW2F2/

works without exceptions:

var each = _.each = _.forEach = function(obj, iterator, context) {
    if (obj == null) return;
...

comment:5 in reply to:  4 Changed 9 years ago by theaspect@…

Replying to theaspect@…:

i've tested and same behavior in Dojo, ExtJS, Mootools

your antispam system sux

same for underscore.js

http://jsfiddle.net/BW2F2/

works without exceptions:

var each = _.each = _.forEach = function(obj, iterator, context) {
    if (obj == null) return;
...

comment:6 Changed 9 years ago by Rick Waldron

Component: unfiledcore
Resolution: wontfix
Status: newclosed

This is intended and expected behaviour

comment:7 Changed 8 years ago by Rick Waldron

#9974 is a duplicate of this ticket.

comment:8 Changed 8 years ago by Rick Waldron

#9989 is a duplicate of this ticket.

Note: See TracTickets for help on using tickets.