#13068 closed bug (notabug)
$.each wraps values into objects
Reported by: | 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 10 years ago by
Resolution: | → notabug |
---|---|
Status: | new → closed |
comment:2 Changed 10 years ago by
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 10 years ago by
If you just use $.each( arr, function( index, elem ) { }), the second arg is always what you expect.
From the docs:
http://api.jquery.com/jquery.each/