myObj.FirstName = 'Phillip',
myObj.LastName = 'Senn';
for (var X in myObj) // FirstName LastName
for each (var X in myObj) // Phillip Senn
Q: Mentally, how do you read these two statements?
Definition and Usage The each() method specifies a function to run for each matched element. Tip: return false can be used to stop the loop early.
The each() method in jQuery specifies a function that runs for every matched element. It is one of the widely used traversing methods in JQuery. Using this method, we can iterate over the DOM elements of the jQuery object and can execute a function for every matched element.
Learn how to loop through elements, arrays and objects with jQuery using the $. each() function, jQuery's foreach equivalent. jQuery's foreach equivalent can be very useful for many situations. These examples will get you started and teach you how you can loop through arrays, objects and all kinds of HTML elements.
To break a $. each or $(selector). each loop, you have to return false in the loop callback. Returning true skips to the next iteration, equivalent to a continue in a normal loop.
The first one (for ( in )
) is reading property names from the object.
So you may read it as for each property in myObj
, assign it to x
.
The second one (for each ( in )
) is reading values of the properties in the object.
This one may be read as for each property's value in myObj
, assign it to x
.
Note that for each
has limited browser support.
Also note that if extra properties are appearing in for ( in )
, it is because it will look up the prototype chain for extra enumerable properties (and someone may have augmented Object
, for example).
You can mitigate this with...
for (var x in myObj) {
if ( ! myObj.hasOwnProperty(x)) {
continue;
}
// Now you are sure the property is of `myObj`
}
jsFiddle.
for (var a in b)
is a way for getting the indices a
of the given array b
. When I'm muttering to myself as I read through code, I usually say something like "for every X
in myObj
".
If you use the each
keyword, you will retrieve the values of the object (or array) in myObj
. If you omit it, myObj
will contain the keys (or array indices).
for(var X in myObj)
For every member (key) in myObj
for each(var X in myObj)
For each member in myObj, get its value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With