Bug Tracker

Opened 7 years ago

Closed 7 years ago

Last modified 7 years ago

#13068 closed bug (notabug)

$.each wraps values into objects

Reported by: joel.dumas@… 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/

Change History (4)

comment:1 Changed 7 years ago by Rick Waldron

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/

comment:2 Changed 7 years ago by joel.dumas@…

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

comment:3 Changed 7 years ago by ajpiano

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

comment:4 Changed 7 years ago by dmethvin

#13202 is a duplicate of this ticket.

Note: See TracTickets for help on using tickets.