Skip to main content

Bug Tracker

Side navigation

#13068 closed bug (notabug)

Opened December 17, 2012 01:33PM UTC

Closed December 17, 2012 01:50PM UTC

Last modified January 12, 2013 04:53PM UTC

$.each wraps values into objects

Reported by: joel.dumas@elca.ch Owned by:
Priority: undecided Milestone: None
Component: unfiled Version: 1.8.3
Keywords: Cc:
Blocked by: Blocking:
Description

Using $.each to iterate over an array of values (tested with strings) wraps them into objects (i.e. what you get with new String("xyz")).

This is very subtle, but there are important differences between the two and when it bites you you can have a very hard time figuring out what happens. For instance, the following assertion is wrong:

$.each(array, function(index) { array[index] === this })

As another example with jQuery 1.6, $("<div>").text("abc") works, but $("<div>").text(new String("abc")) does not. When this is done with a local variable the difference between the two is very hard to spot. (Note that the $.text function has been fixed to accept String objects since then and this particular example works in jQuery 1.8. -- But other pieces of code could be affected in a similar way.)

The minimal test case:

http://jsfiddle.net/7XkvP/2/

Attachments (0)
Change History (4)

Changed December 17, 2012 01:50PM UTC by rwaldron comment:1

resolution: → notabug
status: newclosed

From the docs:

(The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.) The method returns its first argument, the object that was iterated.

http://api.jquery.com/jquery.each/

Changed December 17, 2012 01:54PM UTC by joel.dumas@elca.ch comment:2

Didn't notice this remark. It's a good gotcha (and the SignalR devs fell for it).

But if javascript always wraps this into an object I suppose there's nothing we can do about it :(

JS is really a language full of traps :(

Changed December 17, 2012 02:13PM UTC by ajpiano comment:3

If you just use $.each( arr, function( index, elem ) { }), the second arg is always what you expect.

Changed January 12, 2013 04:53PM UTC by dmethvin comment:4

#13202 is a duplicate of this ticket.