#8547 closed bug (wontfix)
$.each behaviour with null object
Reported by: | 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 12 years ago by
comment:2 Changed 12 years ago by
@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 12 years ago by
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 follow-up: 5 Changed 12 years ago by
same for underscore.js
works without exceptions:
var each = _.each = _.forEach = function(obj, iterator, context) { if (obj == null) return; ...
comment:5 Changed 12 years ago by
Replying to [email protected]…:
i've tested and same behavior in Dojo, ExtJS, Mootools
your antispam system sux
same for underscore.js
works without exceptions:
var each = _.each = _.forEach = function(obj, iterator, context) { if (obj == null) return; ...
comment:6 Changed 12 years ago by
Component: | unfiled → core |
---|---|
Resolution: | → wontfix |
Status: | new → closed |
This is intended and expected behaviour
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.