현재 번역은 완벽하지 않습니다. 한국어로 문서 번역에 동참해주세요.

배열은 하나의 변수에 다수의 데이터를 저장하는 좋은 방법이며, 이 글에서 배열의 생성, 검색, 추가, 삭제 등과 같은 내용을 통해 배열에 대해 알아볼 것입니다.

선행요소: 기초 컴퓨터 활용지식, HTML, CSS 그리고 JavaScript에 대한 기초 지식.
목적: 배열이 무엇인지 이해를 하고 JavaScript에서 어떻게 활용하는지 배운다.

배열이란?

배열은 다수의 변수들을 가지고 있는 하나의 객체이다("list-like objects"). 배열 객체는 변수에 저장 해서 사용 할 수 있고, 변수에 저장된 다른 값들과 거의 동일한 방식으로 쓸 수 있다. 일반적인 값들과 배열의 다른점은 내부의 값에 각각 접근할 수 있으며, 루프를 통해 매우 효율적으로 작업이 가능하다는 것이다. 예를 들어 우리가 흔히 보는 영수증의 제품목록, 가격 등이 배열이라고 볼 수 있으며 그 가격들의 총합을 루프를 통하여 구할 수 있다.

만약 배열이 없다면 다수의 값이 있을 때 각 값의 하나의 변수에 일일이 저장해야 하는 문제가 생길 것이며, 해당 값들을 출력하거나 연산할 때 한땀한땀 개고생 해야한다. 이때문에 코드를 작성하는데 오래걸리며, 비효율적이고 실수를 할 가능성이 높아진다. 오늘 산 물건이 10개 정도라면 값을 더하는데 얼마 걸리지 않겠지만, 100개나 1000개 쯤 구입을 했다면? 잠은 다잔거다.

이전에 배웠던 것처럼, JavaScript 콘솔에서 몇가지 예제를 통해 배열의 쌩기초 부터 알아보자. 아래에 우리가 제공하는 콘솔이 하나 있다.(이 콘솔을 새 탭이나 창을 열어서 사용 하거나, 당신이 선호하는 개발자 콘솔을 사용하면된다.)

배열 만들기

배열은 대괄호로 구성되며 쉼표로 구분 된 항목들을 포함합니다.

  1. 쇼핑 목록을 배열에 저장하고 싶다면 다음과 같이하면됩니다. 콘솔에 다음 행을 입력하십시오.
    var shopping = ['bread', 'milk', 'cheese', 'hummus', 'noodles'];
    shopping;
  2. 아래 배열의 각 항목은 문자열이지만 배열의 모든 항목 (문자열, 숫자, 개체, 다른 변수, 심지어 다른 배열)을 저장할 수 있습니다. 동일한 형태의 항목만 넣거나(아래 sequence처럼)  다양한 형태의 항목을 함께 넣을수(아래 random 처럼) 있습니다. 모두 숫자, 문자열 등일 필요는 없습니다. 다음을 입력해보세요.
    var sequence = [1, 1, 2, 3, 5, 8, 13];
    var random = ['tree', 795, [0, 1, 2]];
  3. 다음으로 넘어가기 전 여러분 마음대로 배열을 만들어 보세요

Accessing and modifying array items

You can then access individual items in the array using bracket notation, in the same way that you accessed the letters in a string.

  1. Enter the following into your console:
    shopping[0];
    // returns "bread"
  2. You can also modify an item in an array by simply giving a single array item a new value. Try this:
    shopping[0] = 'tahini';
    shopping;
    // shopping will now return [ "tahini", "milk", "cheese", "hummus", "noodles" ]
    Note: We've said it before, but just as a reminder — computers start counting from 0!
  3. Note that an array inside an array is called a multidimensional array. You can access an item inside an array that is itself inside another array by chaining two sets of square brackets together. For example, to access one of the items inside the array that is the third item inside the random array (see previous section), we could do something like this:
    random[2][2];
  4. Try further playing with, and making some more modifications to, your array examples before moving on.

Finding the length of an array

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:

sequence.length;
// should return 7

This has other uses, but it is most commonly used to tell a loop to keep going until it has looped through all the items in an array. So for example:

var sequence = [1, 1, 2, 3, 5, 8, 13];
for (var i = 0; i < sequence.length; i++) {
  console.log(sequence[i]);
}

You'll learn about loops properly in a future article, but briefly, this code is saying:

  1. Start looping at item number 0 in the array.
  2. Stop looping at the item number equal to the length of the array. This will work for an array of any length, but in this case it will stop looping at item number 7 (this is good, as the last item — which we want the loop to cover — is 6.
  3. For each item, print it out to the browser console with console.log().

Some useful array methods

In this section we'll look at some rather useful array-related methods that allow us to split strings into array items and vice versa, and add new items into arrays.

Converting between strings and arrays

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.

Note: Okay, this is technically a string method, not an array method, but we've put it in with arrays as it goes well here.

  1. Let's play with this, to see how it works. First, create a string in your console:
    var myData = 'Manchester,London,Liverpool,Birmingham,Leeds,Carlisle';
  2. Now let's split it at each comma:
    var myArray = myData.split(',');
    myArray;
  3. Finally, try finding the length of your new array, and retrieving some items from it:
    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
  4. You can also go the opposite way using the join() method. Try the following:
    var myNewString = myArray.join(',');
    myNewString;
  5. Another way of converting an array to a string is to use the toString() method. toString() is arguably simpler than join() as it doesn't take a parameter, but more limiting. With join() you can specify different separators (try running Step 4 with a different character than a comma).
    var dogNames = ['Rocket','Flash','Bella','Slugger'];
    dogNames.toString(); //Rocket,Flash,Bella,Slugger

Adding and removing array items

We've not yet covered adding and removing array items — let us look at this now. We'll use the myArray array we ended up with in the last section. If you've not already followed that section, create the array first in your console:

var myArray = ['Manchester', 'London', 'Liverpool', 'Birmingham', 'Leeds', 'Carlisle'];

First of all, to add or remove an item at the end of an array we can use push() and pop() respectively.

  1. Let's use push() first — note that you need to include one or more items that you want to add to the end of your array. Try this:
    myArray.push('Cardiff');
    myArray;
    myArray.push('Bradford', 'Brighton');
    myArray;
    
  2. 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:
    var newLength = myArray.push('Bristol');
    myArray;
    newLength;
  3. Removing the last item from the array is as simple as running pop() on it. Try this:
    myArray.pop();
  4. The item that was removed is returned when the method call completes. To save that item in a new variable, you could do this:
    var removedItem = myArray.pop();
    myArray;
    removedItem;

unshift() and shift() work in exactly the same way as push() and pop(), respectively, except that they work on the beginning of the array, not the end.

  1. First unshift() — try the following commands:
    myArray.unshift('Edinburgh');
    myArray;
  2. Now shift(); try these!
    var removedItem = myArray.shift();
    myArray;
    removedItem;

Active learning: Printing those products!

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:

  1. Below the // 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.
  2. On the same line as the // number 2 comment is the beginning of a for loop. In this line we currently have i <= 0, which is a conditional test that causes the for loop to stop immediately, because it is saying "stop when i is no longer less than or equal to 0", and i starts at 0. We'd like you to replace this with a conditional test that stops the loop when i is no longer less than the products array's length.
  3. Just below the // 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.
  4. As part of the above line of code, you'll also want to convert the price from a string to a number. If you can't remember how to do this, check out the first strings article.
  5. There is a variable called 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.
  6. We want you to change the line just below // 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.

Active learning: Top 5 searches

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.

Note: 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:

  1. Add a line below the // 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.
  2. Add a line below the // number 2 comment that removes the value currently at the end of the array.

Conclusion

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.

See also

  • Indexed collections — an advanced level guide to arrays and their cousins, typed arrays.
  • Array — the Array object reference page — for a detailed reference guide to the features discussed in this page, and many more.

 

In this module

 

문서 태그 및 공헌자

 이 페이지의 공헌자: limkukhyun, SSJ-unclear
 최종 변경: limkukhyun,