Let's see how the $each
function helps us to list down our dream cars:
Let's set up the structure of the
$each
function. As our target object, we pass the argument ofmyCars. priority
a the current item value, andcar
the current object's key.$each(myCars, function(priority, car){ // Code to print out each car goes here. });
We'll use the
.write()
method to display the contents ofmyCars
.$each(myCars, function(priority, car){ document.write('<strong>Priority:</strong> '+priority+', <strong>Car name:</strong> '+car+'<br />'); });
Preview the script in your browser, and voila, you've got a list of my dream cars.
We explored a quicker way of iterating through objects using the $each
function. $each
can be used on any objects that are iterable, including arrays and class objects. The $each
function saves you time in having to write complex, nested for
and while
loops.