In the final article of this module, we'll look at arrays — a neat way of storing a list of data items under a single variable name. Here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.
| Prerequisites: | Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what JavaScript is. |
|---|---|
| Objective: | To understand what arrays are and how to manipulate them in JavaScript. |
Arrays are generally described as "list-like objects"; they are basically single objects that contain multiple values stored in a list. Array objects can be stored in variables and dealt with in much the same way as any other type of value, the difference being that we can access each value inside the list individually, and do super useful and efficient things with the list, like loop through it and do the same thing to every value. Maybe we've got a series of product items and their prices stored in an array, and we want to loop through them all and print them out on an invoice, while totaling all the prices together and printing out the total price at the bottom.
If we didn't have arrays, we'd have to store every item in a separate variable, then call the code that does the printing and adding separately for each item. This would be much longer to write out, less efficient, and more error-prone. If we had 10 items to add to the invoice it would already be annoying, but what about 100 items, or 1000? We'll return to this example later on in the article.
As in previous articles, let's learn about the real basics of arrays by entering some examples into browser developer console .
Arrays consist of square brackets and items that are separated by commas.
const shopping = ['bread', 'milk', 'cheese', 'hummus', 'noodles'];
console.log(shopping);
const sequence = [1, 1, 2, 3, 5, 8, 13];
const random = ['tree', 795, [0, 1, 2]];
You can find out the length of an array (how many items are in it) in exactly the same way as you find out the length (in characters) of a string — by using the
length
property. Try the following:
const shopping = ['bread', 'milk', 'cheese', 'hummus', 'noodles'];
console.log(shopping.length); // 5
Items in an array are numbered, starting from zero. This number is called the item's index . So the first item has index 0, the second has index 1, and so on. You can access individual items in the array using bracket notation and supplying the item's index, in the same way that you accessed the letters in a string .
const shopping = ['bread', 'milk', 'cheese', 'hummus', 'noodles'];
console.log(shopping[0]);
// returns "bread"
const shopping = ['bread', 'milk', 'cheese', 'hummus', 'noodles'];
shopping[0] = 'tahini';
console.log(shopping);
// shopping will now return [ "tahini", "milk", "cheese", "hummus", "noodles" ]
注意: We've said it before, but just as a reminder — computers start counting from 0!
random
array (see previous section), we could do something like this:
const random = ['tree', 795, [0, 1, 2]];
random[2][2];
This is fine if you know the index of an item, but what if you don't? You can find the index of a particular item using the
indexOf()
method. This takes an item as an argument and returns the index, or
-1
if the item was not found in the array:
const birds = ['Parrot', 'Falcon', 'Owl'];
console.log(birds.indexOf('Owl')); // 2
console.log(birds.indexOf('Rabbit')) // -1
To add one or more items to the end of an array we can use
push()
. Note that you need to include one or more items that you want to add to the end of your array.
const myArray = ['Manchester', 'Liverpool'];
myArray.push('Cardiff');
console.log(myArray); // [ "Manchester", "Liverpool", "Cardiff" ]
myArray.push('Bradford', 'Brighton');
console.log(myArray); // [ "Manchester", "Liverpool", "Cardiff", "Bradford", "Brighton" ]
The new length of the array is returned when the method call completes. If you wanted to store the new array length in a variable, you could do something like this:
const myArray = ['Manchester', 'Liverpool'];
const newLength = myArray.push('Bristol');
console.log(myArray); // [ "Manchester", "Liverpool", "Bristol" ]
console.log(newLength); // 3
To add an item to the start of the array, use
unshift()
:
const myArray = ['Manchester', 'Liverpool'];
myArray.unshift('Edinburgh');
console.log(myArray); // [ "Edinburgh", "Manchester", "Liverpool" ]
To remove the last item from the array, use
pop()
.
const myArray = ['Manchester', 'Liverpool'];
myArray.pop();
console.log(myArray); // [ "Manchester" ]
pop()
method returns the item that was removed. To save that item in a new variable, you could do this:
const myArray = ['Manchester', 'Liverpool'];
const removedItem = myArray.pop();
console.log(removedItem); // "Liverpool"
To remove the first item from an array, use
shift()
:
const myArray = ['Manchester', 'Liverpool'];
myArray.shift();
console.log(myArray); // [ "Liverpool" ]
If you know the index of an item, you can remove it from the array using
splice()
:
const myArray = ['Manchester', 'Liverpool', 'Edinburgh', 'Carlisle'];
const index = myArray.indexOf('Liverpool');
if (index !== -1) {
myArray.splice(index, 1);
}
console.log(myArray); // [ "Manchester", "Edinburgh", "Carlisle" ]
In this call to
splice()
, the first argument says where to start removing items, and the second argument says how many items should be removed. So you can remove more than one item:
const myArray = ['Manchester', 'Liverpool', 'Edinburgh', 'Carlisle'];
const index = myArray.indexOf('Liverpool');
if (index !== -1) {
myArray.splice(index, 2);
}
console.log(myArray); // [ "Manchester", "Carlisle" ]
Very often you will want to access every item in the array. You can do this using the
for...of
语句:
const birds = ['Parrot', 'Falcon', 'Owl'];
for (const bird of birds) {
console.log(bird);
}
Sometimes you will want to do the same thing to each item in an array, leaving you with an array containing the changed items. You can do this using
map()
. The code below takes an array of numbers and doubles each number:
function double(number) {
return number * 2;
}
const numbers = [5, 2, 7, 6];
const doubled = numbers.map(double);
console.log(doubled); // [ 10, 4, 14, 12 ]
We give a function to the
map()
,和
map()
calls the function once for each item in the array, passing in the item. It then adds the return value from each function call to a new array, and finally returns the new array.
Sometimes you'll want to create a new array containing only the items in the original array that match some test. You can do this using
filter()
. The code below takes an array of strings and filters out all strings that are less than 8 characters long:
function isLong(city) {
return city.length > 8;
}
const cities = ['London', 'Liverpool', 'Totnes', 'Edinburgh'];
const longer = cities.filter(isLong);
console.log(longer); // [ "Liverpool", "Edinburgh" ]
像
map()
, we give a function to the
filter()
方法,和
filter()
calls this function for every item in the array, passing in the item. If the function returns
true
, then the item is added to a new array. Finally it returns the new array.
Often you'll be presented with some raw data contained in a big long string, and you might want to separate the useful items out into a more useful form and then do things to them, like display them in a data table. To do this, we can use the
split()
method. In its simplest form, this takes a single parameter, the character you want to separate the string at, and returns the substrings between the separator as items in an array.
注意: Okay, this is technically a string method, not an array method, but we've put it in with arrays as it goes well here.
const myData = 'Manchester,London,Liverpool,Birmingham,Leeds,Carlisle';
const myArray = myData.split(',');
myArray;
myArray.length;
myArray[0]; // the first item in the array
myArray[1]; // the second item in the array
myArray[myArray.length-1]; // the last item in the array
join()
method. Try the following:
const myNewString = myArray.join(',');
myNewString;
toString()
方法。
toString()
is arguably simpler than
join()
as it doesn't take a parameter, but more limiting. With
join()
you can specify different separators, whereas
toString()
always uses a comma. (Try running Step 4 with a different character than a comma.)
const dogNames = ['Rocket','Flash','Bella','Slugger'];
dogNames.toString(); // Rocket,Flash,Bella,Slugger
Let's return to the example we described earlier — printing out product names and prices on an invoice, then totaling the prices and printing them at the bottom. In the editable example below there are comments containing numbers — each of these marks a place where you have to add something to the code. They are as follows:
// number 1
comment are a number of strings, each one containing a product name and price separated by a colon. We'd like you to turn this into an array and store it in an array called
products
.
// number 2
comment, start a
for...of()
loop to go through every item in the
products
数组。
// number 3
comment we want you to write a line of code that splits the current array item (
name:price
) into two separate items, one containing just the name and one containing just the price. If you are not sure how to do this, consult the
Useful string methods
article for some help, or even better, look at the
Converting between strings and arrays
section of this article.
total
that is created and given a value of 0 at the top of the code. Inside the loop (below
// number 4
) we want you to add a line that adds the current item price to that total in each iteration of the loop, so that at the end of the code the correct total is printed onto the invoice. You might need an
assignment operator
to do this.
// number 5
so that the
itemText
variable is made equal to "current item name — $current item price", for example "Shoes — $23.99" in each case, so the correct information for each item is printed on the invoice. This is just simple string concatenation, which should be familiar to you.
// number 6
comment, you'll need to add a
}
to mark the end of the
for...of()
循环。
A good use for array methods like
push()
and
pop()
is when you are maintaining a record of currently active items in a web app. In an animated scene for example, you might have an array of objects representing the background graphics currently displayed, and you might only want 50 displayed at once, for performance or clutter reasons. As new objects are created and added to the array, older ones can be deleted from the array to maintain the desired number.
In this example we're going to show a much simpler use — here we're giving you a fake search site, with a search box. The idea is that when terms are entered in the search box, the top 5 previous search terms are displayed in the list. When the number of terms goes over 5, the last term starts being deleted each time a new term is added to the top, so the 5 previous terms are always displayed.
注意: In a real search app, you'd probably be able to click the previous search terms to return to previous searches, and it would display actual search results! We are just keeping it simple for now.
To complete the app, we need you to:
// number 1
comment that adds the current value entered into the search input to the start of the array. This can be retrieved using
searchInput.value
.
// number 2
comment that removes the value currently at the end of the array.
You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Arrays .
After reading through this article, we are sure you will agree that arrays seem pretty darn useful; you'll see them crop up everywhere in JavaScript, often in association with loops in order to do the same thing to every item in an array. We'll be teaching you all the useful basics there are to know about loops in the next module, but for now you should give yourself a clap and take a well-deserved break; you've worked through all the articles in this module!
The only thing left to do is work through this module's assessment, which will test your understanding of the articles that came before it.
数组
— the
数组
object reference page — for a detailed reference guide to the features discussed in this page, and many more.
最后修改: , 由 MDN 贡献者