Caution
Some of the array methods have the same name—and almost the same function— as string methods of the same name. Be aware of what data type you are working with, or your script might not function as you would like.
Table 6.1 contains some of the more commonly used methods of the array object.
TABLE 6.1 Some Useful Array Methods concat()
concat() method too:
Click he re to vie w code image
var myOtherArray = ['Thursday','Friday']; var myWeek = myArray.concat(myOtherArray);
// myWeek will contain 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'
join()
To join all of an array’s elements together into a single string, we can use the join() method:
Click he re to vie w code image
var longDay = myArray.join(); // returns MondayTuesdayWednesday
Optionally, we can pass a string argument to this method; the passed string will then be inserted as a separator in the returned string:
Click he re to vie w code image
var longDay = myArray.join("-"); // returns Monday-Tuesday-Wednesday
toString()
toString() is almost a special case of join()—it returns the array as a string with the elements separated by commas:
Click he re to vie w code image
var longDay = myArray.toString(); // returns Monday,Tuesday,Wednesday
indexOf()
We can use indexOf() to find the first place where a particular element occurs in an array. The method returns the index of the searched-for element, or -1 if it isn’t found anywhere in the array:
Click he re to vie w code image
myArray.indexOf('Tuesday') // returns 1 (remember, arrays start with index 0)
myArray.indexOf('Sunday') // returns -1
lastIndexOf()
As you might expect, lastIndexOf() works just the same way as indexOf(), but finds the last occurrence in the array of the search term, rather than the first occurrence.
slice()
slice(), passing to it the starting index and the number of elements we want to retrieve:
Click he re to vie w code image
var myShortWeek = myWeek.slice(1, 3);
//myShortWeek contains 'Tuesday', 'Wednesday', 'Thursday'
sort()
We can use sort() to carry out an alphabetical sort:
Click he re to vie w code image
myWeek.sort() // returns 'Friday', 'Monday', 'Thursday', 'Tuesday', 'Wednesday'
splice()
To add or delete specific items from the array, we can use splice(). The syntax is a little more complex than that of the previous examples:
Click he re to vie w code image
array.splice(index, howmany, [new elements]);
The first element sets the location in the array where we want to perform the splice; the second element, how many items to remove (if set to 0, none are deleted), and
thereafter, an optional list of any new elements to be inserted.
myWeek.splice(2,1,"holiday")
The preceding line of code moves to the array item with index 2 (‘Wednesday’), removes one element (‘Wednesday’), and inserts a new element (‘holiday’); so myWeek now contains ‘Monday’, ‘Tuesday’, ‘holiday’, ‘Thursday’, ‘Friday’. The method returns any removed elements.
Caution
Using splice() changes the original array! If you need to preserve the array for use elsewhere in your code, copy the array to a new variable before executing splice().
Try it Yourself: Array Manipulation
Let’s put some of these methods to work. In your text editor, create the script listed in Listing 6.1 and save it as array.html.
Click he re to vie w code image
<!DOCTYPE html> <html>
<head>
<title>Strings and Arrays</title> <script>
function wrangleArray() {
var sentence = "JavaScript is a really cool language"; var newSentence = "";
//Write it out
document.getElementById("div1").innerHTML = "<p>" + sentence + " </p>";
//Convert to an array
var words = sentence.split(" ");
// Remove 'really' and 'cool', and add 'powerful' instead var message = words.splice(3,2,"powerful");
// use an alert to say what words were removed alert('Removed words: ' + message);
// Convert the array to a string, and write it out
document.getElementById("div2").innerHTML = "<p>" + words.join(" ") + "</p>"; } </script> </head> <body> <div id="div1"></div> <div id="div2"></div> <script>wrangleArray();</script> </body> </html>
As we work through this listing, you may want to refer to the definitions of the individual string and array methods given earlier in the hour, and the discussion of getElementById() and innerHTML from Hour 4, “DOM Objects and Built-in Objects.”
Stepping through the function wrangleArray(), we first define a string:
Click he re to vie w code image
var sentence = "JavaScript is a really cool language";
After writing it out to any empty <div> element using innerHTML, we apply the split() method to the string, passing to it a single space as an argument. The method returns an array of elements, created by splitting the string wherever a space occurs—that is to say, splits it into individual words. We store that array in the variable words.
We next apply the splice() array method to the words array, removing two words at array index 3, “really” and “cool”. Since the splice() method
returns any deleted words, we can display these in an alert() dialog:
Click he re to vie w code image
var message = words.splice(3,2,"powerful"); alert('Removed words: ' + message);
Finally, we apply the join() method to the array, once more collapsing it into a string. Since we supply a single space as the argument to join(), the individual words are once more separated by spaces. Finally we output the revised sentence to a second <div> element by using innerHTML.
The wrangleArray() function is called by a small script in the body of the document:
Click he re to vie w code image
<script>wrangleArray();</script>
The script operation is shown in Figure 6.1.
FIGURE 6.1 Output from array manipulation script
Summary
An array is a convenient means of storing multiple values in a single variable. In this hour, you learned about some of the methods of creating and working with JavaScript array objects.
Q. Does JavaScript allow associative arrays?
A. JavaScript does not directly support associative arrays (arrays with named
indexes). However, there are ways to simulate their behavior by using objects. You see examples of this later in the book.
Q. Can I create a multidimensional array in JavaScript?
A. You can create an array of arrays, which amounts to the same thing:
Click he re to vie w code image
var myArray = [[1,2], [3,4], [5,6]];
alert(myArray[1][0]); // alerts '3'
Workshop
Try to answer all the questions before reading the subsequent “Answers” section.
Quiz
1. If the element with highest index in array Foo is Foo[8], what value will be
returned by Foo.length?
2. You have an array called monthNames containing the names of all the months
of the year. How would you use join() to create a string name containing all of these month names with a single space between names?
3. What value will be returned by indexOf() if it is passed a value that does not
appear in the array to which it is applied?
Answers
1. Foo.length will return 9.
2. var names = monthNames.join(" ");
3. It will return -1.
Exercise
Review the array and string methods that share a method name. Familiarize yourself with how the syntax and operation changes depending on whether these methods are applied to a string or an array.
Hour 7. Program Control
What You’ll Learn in This Hour:
Using conditional statements
Comparing values with comparison operators Applying logical operators
Writing loops and control structures Setting Timers in JavaScript
In Hour 5, “Numbers and Strings,” and Hour 6, “Arrays,” you took a quick trip through the data types that JavaScript variables can contain. To create anything but the simplest scripts, though, you’re going to need your code to make decisions based on those values. In this hour we examine ways to recognize particular conditions and have our program act in a prescribed way as a result.