Array
Sometimes it makes sense to store multiple variable values under a single variable name. JavaScript has the array data type to help you do this.
An array is a type of object used for storing multiple values in a single variable. Each value has a numeric index that may contain data of any data type—Booleans, numbers, strings, functions, objects, and even other arrays.
Creating a New Array
The syntax used for creating an array will already be familiar to you; after all, an array is simply another object:
var myArray = new Array();
However, for arrays there is a shorthand version—simply use square brackets ([]) like this:
var myArray = [];
Initializing an Array
You can optionally preload data into your array at the time it is created:
var myArray = ['Monday', 'Tuesday', 'Wednesday'];
Alternatively, items can be added after the array has been created:
var myArray = []; myArray[0] = 'Monday'; myArray[1] = 'Tuesday'; myArray[2] = 'Wednesday';
Array length
All arrays have a length property that tells how many items the array contains. The length property is automatically updated when you add items to or remove items from the array. The following code returns the length of the preceding array:
myArray.length // returns 3
myArray[50] = 'Ice cream day'; myArray.length now returns 51,
even though the array only has four entries.
Array Methods
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.
contains some of the more commonly used methods of the array object.
concat()
You’ve already had experience with string concatenation, and JavaScript arrays have a concat() method too:
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:
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:
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:
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:
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()
When we need to create an array that is a subset of our starting array, we can use slice(), passing to it the starting index and the number of elements we want to retrieve:
var myShortWeek = myWeek.slice(1, 3); //myShortWeek contains 'Tuesday', 'Wednesday', 'Thursday'
sort()
We can use sort() to carry out an alphabetical sort:
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:
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.
Array Manipulation
<!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>