Chapter 11

Creating and Changing Arrays

Who doesn’t like lists? Lists are everywhere and we use them all the time in our day-to-day lives. Whether you’re keeping track of your favorite songs, writing down everything you have to get done today, or viewing the top ten cutest animal pictures on the Internet, lists help us organize and make sense of the world.

In computer programming, we use something called an array to store lists of data. In this chapter, we show you how to create arrays, how to change the values in arrays, and how to work with arrays to do useful things inside your programs.

image

What Are Arrays?

Arrays are a special kind of variable that can hold multiple values using the same name. You can picture an array as being similar to a dresser with multiple drawers. Each drawer can hold something different, but the whole thing is still your dresser.

If you want to tell someone which drawer to look in for socks, you can say, “The socks are in the top drawer.” If they’re in the next drawer down, you’d say, “They’re in the second drawer from the top.” If you were to make a list showing what’s in each drawer of your dresser, you would do something like this:

  • Top drawer: Socks
  • Second drawer: Shirts
  • Third drawer: Pants

If you understand how your dresser organizes your clothes, you have a good start on understanding how JavaScript arrays organize data.

If we wanted to create a JavaScript array to describe the contents of the dresser, we could use the following code:

var dresser = ["socks","shirts","pants"];

This statement creates three “drawers” (or elements, as they’re called in JavaScript). When you want to know what’s in each of the elements, you can simply ask JavaScript. For example, to find out what’s in the third element, you use the following:

dresser[2]

The value of dresser[2] is pants.

remember As we talk about in Chapter 3, JavaScript starts counting from zero. So, the first element of an array is number 0, the second is 1, and the third is 2.

technicalstuff The maximum number of elements that a JavaScript array can hold is 4.29 billion. So, pretty much anything that you want to list will fit into an array!

Now that you understand how arrays work, let’s talk a bit more about how to create them.

Creating and Accessing Arrays

Creating an array starts the same way as any variable: with the var keyword. However, in order to let JavaScript know that the object you’re making isn’t just a normal variable, you put square brackets after it.

To create an array with nothing inside it, just use empty brackets, like this:

var favoriteFoods = [];

To create an array with data inside it, put values inside the brackets, separated by commas, like this:

var favoriteFoods = ["broccoli","eggplant","tacos","mushrooms"];

Storing different data types

Arrays can hold any of the different data types of JavaScript, including numbers, strings, Boolean values, and objects.

In fact, a single array can contain multiple different data types. For example, the following array definition creates an array containing a number, a string, and a Boolean value:

var myArray = [5, "Hi there", true];

Just as when you create regular variables, string values in arrays must be within either single or double quotes.

Getting array values

To get the value of an array element, use the name of the array, followed by square brackets containing the number of the element you want to retrieve. For example:

myArray[0]

Using the array definition that we created in the last section, this will return the number 5.

Using variables inside arrays

You can also use variables within array definitions. For example, in the following code, we create two variables and then we use that variable inside an array definition:

var firstName = "Neil";

var middleName = "deGrasse"

var lastName = "Tyson";

var Scientist = [firstName, middleName, lastName];

Because variables are stand-ins for values, the result of these three statements is exactly the same as if we were to write the following statement:

var Scientist = ["Neil","deGrasse" "Tyson"];

To find out more about arrays, let’s practice setting, retrieving, and changing array elements in the JavaScript Console.

Changing Array Element Values

JavaScript gives you several ways to modify arrays.

The first way is to give an existing array element a new value. This is as easy as assigning the value. Follow these steps in your JavaScript Console to see how this works:

  1. Create a new array with the following statement:

    var people = ["Teddy","Cathy","Bobby"];

  2. Print out the values of the array elements with this statement:

    console.log(people);

    The JavaScript Console returns the same list of elements that you put in in the previous step.

  3. Change the value of the first element by entering this statement, and then press Return or Enter:

    people[0] = "Georgie";

  4. Print the values of the array’s element now, using the following statement:

    console.log(people);

    The value of the first array element has been changed from "Teddy" to "Georgie".

Now it’s your turn. Can you modify the array so that it contains the following list of names, in this order?

Mary, Bobby, Judy, Eddie, Herbie, Tony

When you have lists of names, or lists of anything, there are many things that you can do with them, such as sorting them, adding to and removing from them, comparing them, and much more. In the next section, we talk about how JavaScript simplifies many of these tasks with array methods.

Working with Array Methods

Array methods are built-in things that can be done with or to JavaScript arrays. These methods are perhaps the best part about working with arrays in JavaScript. Once you know how to use them, you’ll save yourself a lot of time and effort. Plus, they can also be a lot of fun!

JavaScript’s built-in array methods are listed in Table 11-1.

Table 11-1 JavaScript Array Methods

Method

Description

concat()

A new array made up of the current array, joined with other array(s) and/or value(s).

indexOf()

Returns the first occurrence of the specified value within the array. Returns –1 if the value is not found.

join()

Joins all the elements of an array into a string.

lastIndexOf()

Returns the last occurrence of the specified value within the array. Returns –1 if the value is not found.

pop()

Removes the last element in an array.

push()

Adds new items to the end of an array.

reverse()

Reverses the order of elements in an array.

shift()

Removes the first element from an array and returns that element, resulting in a change in length of an array.

slice()

Selects a portion of an array and returns it as a new array.

sort()

Returns an array after the elements in an array are sorted. (The default sort order is alphabetical and ascending.)

splice()

Returns a new array comprised of elements that were added to or removed from a given array.

tostring()

Converts an array to a string.

unshift()

Returns a new array with a new length by the addition of one or more elements.

Learning the Ways of Arrays

Array methods can be difficult to understand without seeing them in action, so let’s go into JSFiddle and try some of them out!

  1. Go to JSFiddle.net in your web browser and log in.
  2. Open the public dashboard at http://jsfiddle.net/user/forkids/fiddles.
  3. Locate the program named “Lesson 11 – Array Methods – Start” and click the title to open it.
  4. Click the Fork link in the top menu to create your own version of the program.
  5. Change the name of your program under Fiddle Options to “(Your Name) Array Methods.”
  6. Click Update and then click Set as Base in the top menu to save your program.

    The program should look like Figure 11-1, with two arrays in the JavaScript pane, two HTML elements in the HTML pane, and a header displaying in the Result pane.

image

Figure 11-1: The starting point for our program.

In this example, we create a simple program that, when run, uses an array method to modify an array or create a new array. The program then outputs the array as a list in the Result pane.

toString() and valueOf()

The toString() and valueOf() methods both do the same thing: They convert the array to a string, with each element separated by a comma.

Our program will use toString() in the statement that tells the browser where to display the array values.

Follow these steps to create the output statement:

  1. Click inside the JavaScript pane and press Return or Enter to insert a couple of line breaks after the statement that creates the otherPeople array.
  2. Type the following on a new line:

    document.getElementById("peopleIKnow").innerHTML = people.toString();

    This statement writes out the values in the people array as a list.

  3. Click the Update button.

    The values in the people array display in the Result pane, as shown in Figure 11-2.

  4. Replace toString() with valueOf() in the JavaScript pane.
  5. Click Update.

    The Result pane should be unchanged, demonstrating that toString() and valueOf() do the same thing to arrays.

image

Figure 11-2: The values in the people array.

concat()

Follow these steps to use the concat() method to join together two arrays:

  1. Type the following statement below the array definitions, but above the output statement:

    people = people.concat(otherPeople);

  2. Click Update.

    The concat() method has added together the people array and the otherPeople array. We then used the assignment operator (=) to store the result of this operation in the people array. The resulting array is shown in Figure 11-3.

image

Figure 11-3: The result of using the concat() operator to add together the two arrays.

indexOf()

The indexOf() array method looks for a value among an array’s elements and returns the position of that array. To try it out with the people array, follow these steps:

  1. Comment out the statement using the concat() method by putting two slashes before the line, as shown in Figure 11-4.

    Commenting out the statement will cause it to not run, but the code will still be there if you want to use it again later.

  2. Type the following statement, which will look for the string "Eddie" in the people array.

    people = people.indexOf("Eddie");

  3. Click the Update button to save and run the program.

    The Result window displays the position in the array of the string, as shown in Figure 11-5.

image

Figure 11-4: Commenting out a statement.

image

Figure 11-5: Finding Eddie.

join()

The join() array method behaves like the toString() and valueOf() methods, in that it joins the elements of an array together. However, the join() method has one very special feature: It lets you specify the character or characters that should come between the elements of the array.

To try out join(), follow these steps:

  1. Comment out the statement using the indexOf() method.
  2. Type the following statement underneath the commented statements:

    people = people.join(" # ");

  3. Click the Update link to save your work and run the program.

    The Result pane should now display the elements in the people array, separated by #, as shown in Figure 11-6.

image

Figure 11-6: Using join().

lastIndexOf()

The lastIndexOf() array method tells you the last array element that contains the specified value.

Notice that our people array contains the name Bobby in both the second and seventh positions (array elements numbers 1 and 6). What value do you think running lastIndexOf() will print out? Use these steps to find out:

  1. Comment out the previous statement, the one using join().
  2. Enter the following statement underneath the commented statements:

    people = people.lastIndexOf("Bobby");

  3. Click Update to save your work and run your code.

    The result window should display the last position of the string "Bobby" in the array, as shown in Figure 11-7.

image

Figure 11-7: The last position of "Bobby".

pop()

The pop() array method removes the last element in an array and returns that element. Do the following steps to see it in action:

  1. Comment out the previous statement.
  2. Enter the following statement underneath the commented ones:

    people = people.pop();

  3. Click Update to save your work and run your code.

    The Result pane displays the last item that was in the original people array.

    Notice that our statement not only removed the last item from the people array, but also set the value of the people array to just that one item. If you want to just remove the last item from an array, continue with the following steps.

  4. Comment out the previous statement.
  5. Type the following underneath the commented statements:

    people.pop();

  6. Click Update to see the result.

    Now, the people list has all the same elements, but with the last one removed (or “popped off”), as shown in Figure 11-8.

image

Figure 11-8: Bobby has been popped off the list.

push()

The push() array method adds an element, or elements, to the end of an array and returns the new number of elements of the array (in other words, its length).

To try out push(), follow these steps:

  1. Comment out the previous statement.
  2. Type the following statement underneath the commented statements:

    people = people.push("Teddy");

  3. Click Update.

    The result window now shows the new length of the people array: 8. By setting the value of people equal to the return value of the push() method, however, we’ve deleted all the elements of the people array. Let’s use push() again, but preserve the elements of the people array this time.

  4. Comment out the previous statement.
  5. Enter the following in order to modify the array without changing its value to the return value:

    people.push("Teddy");

  6. Click Update to see the result.

    A list of the elements in the people array is displayed, with Teddy added to the end, as shown in Figure 11-9.

image

Figure 11-9: The people array with Teddy pushed onto the end.

reverse()

The reverse() method flips your array over. What was the first element becomes the last, what was the last becomes the first, and everything in between reverses, too.

Follow these steps to see reverse() do its thing.

  1. Comment out the previous statement.
  2. Type this statement after the commented statements:

    people = people.reverse();

  3. Click Update.

    The result will display in the Result pane, as shown in Figure 11-10. If you compare the result with the original array, you’ll see that everything is in opposite order.

image

Figure 11-10: Reversing the elements in an array.

shift() and unshift()

The shift() method removes the first element from the array. To try it out, follow these steps:

  1. Comment out the previous statement.
  2. Type this statement after the commented statements:

    people.shift();

  3. Click Update.

    The Result pane displays the new array, with Mary removed from the beginning, as shown in Figure 11-11.

image

Figure 11-11: The shift() method removes the first element.

The shift() method has a twin, called unshift(), which adds an element to the beginning of an array. To use it, follow these steps:

  1. Comment out the previous statement.
  2. Type the following statement after the commented statements:

    people.unshift("Teddy");

  3. Click Update.

    The Result pane shows the people list, with Teddy added at the beginning.

slice()

The slice() method lets you pick certain elements from your array to create a new array. Follow these steps:

  1. Comment out the previous statement.
  2. Type the following after the commented statements:

    people = people.slice(0,3);

  3. Click Update.

    The Result pane shows the elements in the people array after the slice() method, as shown in Figure 11-12.

image

Figure 11-12: The slice() method selects certain elements.

sort()

The sort() method sorts the elements in an array alphabetically. To use sort(), follow these steps:

  1. Comment out the previous statement.
  2. Type the following on a line after the commented statements:

    people = people.sort();

  3. Click the Update link.

    The Result pane shows you that the elements have been re-sorted, alphabetically, as shown in Figure 11-13.

image

Figure 11-13: The elements have been re-sorted.

splice()

The splice() method lets you add or remove elements at certain positions. To try it out, follow these steps:

  1. Comment out the previous statement.
  2. Enter the following after the last commented statement:

    people.splice(1,0,"Cathy");

    What this is saying is to insert the value after the first element, don’t remove any elements (that’s what the 0 means), and insert Cathy.

  3. Click Update.

    In the Result pane, you see that Cathy has been added after Mary, as shown in Figure 11-14.

image

Figure 11-14: Using splice().

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset