xjq233p_1
xjq233p_1

Reputation: 8060

JQuery inconsistency?

I realized that given the following:

foo = {a:'aa', b:'bb'} 

$.each(foo, function(k,v) { ... 
$(foo).each(function(k,v) { ... 

the values of k,v is different in both cases. Is it me that is weird or is jquery inconsistent?

EDIT

If you come here to explain the difference between $.each and $(foo).each, I want to clarify that I know the difference between the two.

Upvotes: 1

Views: 141

Answers (4)

whitneyit
whitneyit

Reputation: 1226

In your first example you are iterating over an Object which equates to:

$.each( foo, function( key, value ) {...

and your second example, you are iterating over a selection of DOM nodes which equates to

 $(foo).each( function( index, element ) {...

I hope that clears things up

Upvotes: 0

user1106925
user1106925

Reputation:

Under the "Working with plain objects" section of the jQuery() docs, there are a number of options, but enumerating with .each() isn't one of them.

Working With Plain Objects

At present, the only operations supported on plain JavaScript objects wrapped in jQuery are: .data(), .prop(), .bind(), .unbind(), .trigger() and .triggerHandler(). The use of .data() (or any method requiring .data()) on a plain object will result in a new property on the object called jQuery{randomNumber} (eg. jQuery123456789).

You should use the generic $.each() enumerator.

Upvotes: 3

Daniel A. White
Daniel A. White

Reputation: 190945

Its because you are "selecting" the object (i.e. DOM stuff) with the second method, not iterating the object.

Upvotes: 0

Matt Lo
Matt Lo

Reputation: 5731

foo alone is an object literal, $(foo) is a jQuery object.

Upvotes: 0

Related Questions