Introduction to JavaScript Fall 2010 Class 8

esse quam videri
Revision as of 19:01, 26 October 2010 by Matthew.ephraim (talk | contribs) (Today's Interesting JavaScript Site)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Back to Introduction to JavaScript Fall 2010

Introduction

In previous classes, we have talked about looking for elements with jQuery. When you use the jQuery function to find an element or multiple elements jQuery will return a jQuery "collection". So far, I haven't talked much about how jQuery collections work. This week, I will show you how to create your own collection of objects, and how to use jQuery to loop over each item in the collection.

Arrays

Let's say that you wanted to create a shopping list using JavaSript. As an example, your shopping list might have the following items: milk, eggs, cheese and flour. Now let's say you wanted to make a function that would take care of the actions for buying each of the items. You might call your function buyStuff.

If you wanted to buy a single item, you could create a buyStuff function that takes one parameter:

 function buyStuff(item1) {
  // buy item 1
 }

Then you could call your function like this:

 buyStuff("milk");

But let's say you wanted to make a function that would buy multiple items. You would have to create a function that had a parameter for each item in your list. In the case of our example list, the function would need to have 4 parameters, 1 for each item in the list.

 function buyStuff(item1, item2, item3, item4) {
   // buy item1
   // buy item2
   // buy item3
   // buy item4
 }

This will work for now, but what if we added sugar to our list? Now the function would need to take in 5 parameters:

 function buyStuff(item1, item2, item3, item4, item5) {
   // buy item1
   // buy item2
   // buy item3
   // buy item4
   // buy item5
 }

This works too, but now you can only have 5 items in your list. What if you wanted 10? Obviously, we need a way to pass a collection of items to the function.

JavaScript allows you to create collections of objects called arrays. Think of an array as a box where you can store things. Using an array, we can create a shopping list of items that can be passed in as single parameter to a function.

Creating an Array

Arrays are created using an open straight bracket ([) and a close straight bracket (]). You can create an empty array and store it in a variable like this:

 var food = [];

An empty array looks a little bit like an empty box, ready to have items added to it.

Adding Items to an Array

To add an item to an array, you use the push function. Push takes in a single object as a parameter. The item you pass in to push will be added as the last item in the array:

 var food = [];
 food.push("milk");
 food.push("eggs");
 food.push("cheese");
 food.push("flour");

In the example above, an empty array called food is created, and multiple items are pushed into it. The first item in the array will be "milk" and the last item in the array will be "eggs".

Array Literals

Individually adding items to an array will work, but sometimes it can be tedious. You can create a new array that already has items in it by using an array literal. An array literal looks like this:

 var food = ["milk", "eggs", "cheese", "flour"];

Notice that the new array still has the open and close brackets, but this time the items for the array are listed between the brackets. Also notice that each item is separated by a comma.

Accessing Array Items

Once you have created an array, it would be nice to get the items out of the array. Each item in an array is numbered. However, instead of starting the numbering with 1, items in an array start with 0. If an array has 4 items, the first item will be number 0 and the last item will be number 3:

 var food = ["milk",   // Item 0
             "eggs",   // Item 1
             "cheese", // Item 2
             "flour"]; // Item 3

To access an item in an array, take the name of the array you created and follow it with an open bracket, the number of the item you want to find, and finally a close bracket:

 alert(food[0]); // Alerts "milk"
 alert(food[1]); // Alerts "eggs"
 alert(food[3]); // Alerts "flour"

If you use the push function to add new items to an array after it has been created, the new items will be added at the end of the array. So, if you add an item to an array that already has 4 items, the new item you add will be given the number 4.

Checking the Number of Items in an Array

If you have an array and you'd like to check the number of items in the array, you can use the array's length property. Just like JavaScript objects, JavaScript arrays have some properties that you can get to through the dot (.) operator. You've already seen the array's push function, which is accessed through the dot operator. The array's length property is accessed through the dot operator as well:

 var food = ["milk", "eggs", "cheese", "flour"];
 
 alert(food.length); // This should alert 4

An empty array has a length of 0 and when you add items to an array the length property will be updated automatically.

Looping Through Array Items

In class 3 I showed you how you could use loops to repeat some code a given number of times. You can also use loops to repeat some code for each item in an array. In the case of arrays, instead of supplying the number of times you'd like a loop to repeat, you will use the array's length property to determine the number of times a loop should repeat.

Remember that loops need to have a variable that is incremented each time the loop runs. In previous examples we have used the variable i, and then checked that i was less than a given number:

 for(var i = 0; i < 20; i++) {
   // run some code
 }

When we loop over an array, we can still use the i variable to count off the number of times the loop has run. However, instead of checking that i is less than a certain number, we will check that it is less than the number of items in the array:

 var food = ["milk", "eggs", "cheese", "flour"];
 
 for(var i = 0; i < food.length; i++) {
   alert(food[i]);
 }

Remember that arrays start their numbering with 0 instead of 1. In the example above, we are using i to find an item in the array food. The loop will alert item 0 first, then item 1, then item 2 and so on. The loop will stop when i is the same as the food.length.

Updating the Shopping List

Remember that, in the example above, we were trying to create function that would buy all of items in a shopping list. Using arrays, we can update the buyStuff function so that it takes in an array as a parameter, and then loops over each item in the array:

 function buyStuff(food) {
   for(var i = 0; i < food.length; i++) {
     buy(food[i]);
   }
 }

Then, we can use the function to buy all of the items on the list:

 var food = ["milk", "eggs", "cheese", "flour"];
 
 buyStuff(food);

With the new buyStuff function, we can update the list with more items withouth having to change the function.

Looping with jQuery

You may have noticed that the syntax for looping over an array is a little bit ugly. jQuery provides a function that makes it easier to loop over arrays, as well as collections of items that you've found on the page.

Wrapping an Array with jQuery

First, to take advantage of jQuery's extra array functionality, you need to wrap your array with jQuery. This is as easy as using jQuery's $ function:

 var food = $(["milk", "eggs", "cheese", "flour"]);

Notice that the new array is created the same as before, but this time it's wrapped with $(). Once an array has be wrapped with jQuery, you can take advantage of the new functions that jQuery provides.

Looping with jQuery

Once of the new functions that jQuery provides is called each. The each function takes in another function that will be called for each item in the array. So, for example, let's say you wanted to alert each item in the array food. First, you need to create a function that will alert each individual item:

 function alertItem() {
  alert(this);
 }

The alertItem function calls the alert function and passes in this. When we used jQuery event handlers, this pointed to the current item that was handling the event. With the each function, this points to the current item in the array. The example below shows how to loop over each item in the food array:

 function alertItem() {
  alert(this);
 }
 
 var food = $(["milk", "eggs", "cheese", "flour"]);
 
 food.each(alertItem);

The each function takes in the name of the alertItem function and calls the function for each item in the array. Every time the function runs, it will point to another item in the array. The first time it runs this will point to "milk". The second time it runs, it will point to "eggs". The function will run until it has been run for every item in the array.

Using each with jQuery Collections

The jQuery each function doesn't just work with arrays. It will also work with the special jQuery collections that are returned when you use jQuery to find elements on the page. For example, if you wanted to alert the html for every list item on the page, you could use the each function to do it:

 function alertHTML() {
   alert($(this).html());
 }
 
 $("li").each(alertHTML);

jQuery will find every list item on the page and call the alertHTML function for each one.

Today's Interesting JavaScript Site

Google JavaScript playground

Activities

Activity 1

  • Create a new page that uses jQuery.
  • Create an unordered list on the page (using the ul tag).
  • Create an array that has the following items: milk, eggs, cheese, flour.
  • Loop through each item in the array and add a new list item for each item.

Activity 2

You can update the code from activity 1 for activity 2

  • Create a new page that uses jQuery.
  • Create 2 unordered lists on the page.
    • One list should have the id "grocery-list".
    • The other list should the id "hardware-list".
  • Create 2 textboxes on the page.
    • One textbox should have the id "grocery".
    • The other textbox should have the id "hardware".
  • Create a button for each textbox.
    • One button should have the id ""add-grocery".
    • The other button should have the id add-hardware.
  • When the add-grocery button is clicked, it should take the value of the grocery textbox and add a new list item to the grocery-list.
  • When the add-hardware button is clicked, it should take the value of the hardware textbox and add a new list item to the hardware-list.