--- title: Arrays slug: Learn/JavaScript/First_steps/Arrays translation_of: Learn/JavaScript/First_steps/Arrays ---
배열은 하나의 변수에 다수의 데이터를 저장하는 좋은 방법이며, 이 글에서 배열의 생성, 검색, 추가, 삭제 등과 같은 내용을 통해 배열에 대해 알아볼 것입니다.
| 선행요소: | 기초 컴퓨터 활용지식, HTML, CSS 그리고 JavaScript에 대한 기초 지식. |
|---|---|
| 목적: | 배열이 무엇인지 이해를 하고 JavaScript에서 어떻게 활용하는지 배운다. |
배열은 다수의 변수들을 가지고 있는 하나의 객체이다("list-like objects"). 배열 객체는 변수에 저장 해서 사용 할 수 있고, 변수에 저장된 다른 값들과 거의 동일한 방식으로 쓸 수 있다. 일반적인 값들과 배열의 다른점은 내부의 값에 각각 접근할 수 있으며, 루프를 통해 매우 효율적으로 작업이 가능하다는 것이다. 예를 들어 우리가 흔히 보는 영수증의 제품목록, 가격 등이 배열이라고 볼 수 있으며 그 가격들의 총합을 루프를 통하여 구할 수 있다.
만약 배열이 없다면 다수의 값이 있을 때 각 값의 하나의 변수에 일일이 저장해야 하는 문제가 생길 것이며, 해당 값들을 출력하거나 연산할 때 한땀한땀 개고생 해야한다. 이때문에 코드를 작성하는데 오래걸리며, 비효율적이고 실수를 할 가능성이 높아진다. 오늘 산 물건이 10개 정도라면 값을 더하는데 얼마 걸리지 않겠지만, 100개나 1000개 쯤 구입을 했다면? 잠은 다잔거다.
이전에 배웠던 것처럼, JavaScript 콘솔에서 몇가지 예제를 통해 배열의 쌩기초 부터 알아보자. 아래에 우리가 제공하는 콘솔이 하나 있다.(이 콘솔을 새 탭이나 창을 열어서 사용 하거나, 당신이 선호하는 개발자 콘솔을 사용하면된다.)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript console</title>
<style>
* {
box-sizing: border-box;
}
html {
background-color: #0C323D;
color: #809089;
font-family: monospace;
}
body {
max-width: 700px;
}
p {
margin: 0;
width: 1%;
padding: 0 1%;
font-size: 16px;
line-height: 1.5;
float: left;
}
.input p {
margin-right: 1%;
}
.output p {
width: 100%;
}
.input input {
width: 96%;
float: left;
border: none;
font-size: 16px;
line-height: 1.5;
font-family: monospace;
padding: 0;
background: #0C323D;
color: #809089;
}
div {
clear: both;
}
</style>
</head>
<body>
</body>
<script>
var geval = eval;
function createInput() {
var inputDiv = document.createElement('div');
var inputPara = document.createElement('p');
var inputForm = document.createElement('input');
inputDiv.setAttribute('class','input');
inputPara.textContent = '>';
inputDiv.appendChild(inputPara);
inputDiv.appendChild(inputForm);
document.body.appendChild(inputDiv);
if(document.querySelectorAll('div').length > 1) {
inputForm.focus();
}
inputForm.addEventListener('change', executeCode);
}
function executeCode(e) {
try {
var result = geval(e.target.value);
} catch(e) {
var result = 'error — ' + e.message;
}
var outputDiv = document.createElement('div');
var outputPara = document.createElement('p');
outputDiv.setAttribute('class','output');
outputPara.textContent = 'Result: ' + result;
outputDiv.appendChild(outputPara);
document.body.appendChild(outputDiv);
e.target.disabled = true;
e.target.parentNode.style.opacity = '0.5';
createInput()
}
createInput();
</script>
</html>
{{ EmbedLiveSample('Hidden_code', '100%', 300, "", "", "hide-codepen-jsfiddle") }}
배열은 대괄호로 구성되며 쉼표로 구분 된 항목들을 포함합니다.
var shopping = ['bread', 'milk', 'cheese', 'hummus', 'noodles']; shopping;
var sequence = [1, 1, 2, 3, 5, 8, 13]; var random = ['tree', 795, [0, 1, 2]];
그런 다음 문자열의 문자에 접근했던 것과 같은 방법으로 괄호 표기법을 사용하여 배열의 개별 항목을 접근 할 수 있습니다.
shopping[0]; // returns "bread"
shopping[0] = 'tahini'; shopping; // shopping will now return [ "tahini", "milk", "cheese", "hummus", "noodles" ]
무작위 배열(random array) 안의 세 번째 항목 인 배열 내부 항목 중 하나에 접근하려면(앞 섹션 참조) 다음과 같이 할 수 있습니다.:
random[2][2];
{{jsxref("Array.prototype.length","length")}} 속성을 사용해서 배열에 들어 있는 문자열의 갯수를 알아낼 수 있다.(갯수가 얼마나 많이 있던지) 다음을 보자.:
sequence.length; // should return 7
다른 용도로 사용되기도 하는데, loop문으로 배열의 모든 항목을 반복적으로 값을 대입하는데 일반적으로 사용한다. 예를 들면:
var sequence = [1, 1, 2, 3, 5, 8, 13];
for (var i = 0; i < sequence.length; i++) {
console.log(sequence[i]);
}
다음 article에서 반복문에 대해서 자세히 다루겠지만 다음과 같이 요약할 수 있다.
console.log()을 사용해 브라우저 콘솔창으로 확인해보세요.이번 섹션에서는 문자열을 배열 항목으로 분할하고, 다시 배열 항목을 문자열로 변환하며 새로운 항목을 배열에 추가할 수 있는 배열 관련 method를 알아봅니다.
프로그램을 만들다보면 종종 긴 문자열로 이루어진 원시 데이터를 제공받게 될 것이고, 원시 데이터를 정제하여 더 유용한 데이터를 추출해 테이블 형태로 표시하는 등 작업을 수행해야 합니다. 이러한 작업을 위해 {{jsxref("String.prototype.split()","split()")}} method를 사용할 수 있습니다. {{jsxref("String.prototype.split()","split()")}} method는 사용자가 원하는 매개변수로 문자열을 분리하여 배열로 표현해줍니다.
Note: 사실 String method이지만, 배열과 함께 사용하기 때문에 여기에 넣었습니다.
var myData = 'Manchester,London,Liverpool,Birmingham,Leeds,Carlisle';
var 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
var myNewString = myArray.join(',');
myNewString;
toString() 은 join() 과 달리 매개변수가 필요 없어서 더 간단하지만, 제한이 더 많습니다. join() 을 사용하면 다른 구분자를 지정할 수 있습니다. (콤마 말고 다른 매개변수를 사용하여 4단계를 실행 해보세요.)
var dogNames = ['Rocket','Flash','Bella','Slugger']; dogNames.toString(); //Rocket,Flash,Bella,Slugger
이번엔 배열에 item을 추가하고 제거하는 방법을 알아볼 차례 입니다. 위에서 만든 myArray 를 다시 사용하겠습니다. 섹션을 순서대로 진행하지 않았다면 아래와 같은 배열을 만들어주세요.:
var myArray = ['Manchester', 'London', 'Liverpool', 'Birmingham', 'Leeds', 'Carlisle'];
먼저, 배열의 맨 끝에 item을 추가하거나 제거하기 위해 각각{{jsxref("Array.prototype.push()","push()")}} and {{jsxref("Array.prototype.pop()","pop()")}} 를 사용할 수 있습니다.
push() 를 사용합니다. — 배열의 끝에 추가할 item을 반드시 하나 이상 포함해야 한다는 점을 기억하고 아래와 같이 따라해보세요:
myArray.push('Cardiff');
myArray;
myArray.push('Bradford', 'Brighton');
myArray;
var newLength = myArray.push('Bristol');
myArray;
newLength;
pop()으로 매우 간단합니다. 아래와 같이 따라해보세요:
myArray.pop();
var removedItem = myArray.pop(); myArray; removedItem;
{{jsxref("Array.prototype.unshift()","unshift()")}} 와{{jsxref("Array.prototype.shift()","shift()")}}는 push() 와 pop()과 유사하게 동작합니다. 다만, 배열의 맨 끝이 아닌 제일 처음 부분의 item을 추가하거나 제거합니다..
unshift() 를 사용해봅니다.:
myArray.unshift('Edinburgh');
myArray;
shift()를 사용해봅니다.!
var removedItem = myArray.shift(); myArray; removedItem;
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 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.// 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 {{anch("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.<h2>Live output</h2>
<div class="output" style="min-height: 150px;">
<ul>
</ul>
<p></p>
</div>
<h2>Editable code</h2>
<p class="a11y-label">Press Esc to move focus away from the code area (Tab inserts a tab character).</p>
<textarea id="code" class="playable-code" style="height: 410px;width: 95%">
var list = document.querySelector('.output ul');
var totalBox = document.querySelector('.output p');
var total = 0;
list.innerHTML = '';
totalBox.textContent = '';
// number 1
'Underpants:6.99'
'Socks:5.99'
'T-shirt:14.99'
'Trousers:31.99'
'Shoes:23.99';
for (var i = 0; i <= 0; i++) { // number 2
// number 3
// number 4
// number 5
itemText = 0;
var listItem = document.createElement('li');
listItem.textContent = itemText;
list.appendChild(listItem);
}
totalBox.textContent = 'Total: $' + total.toFixed(2);
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset">
<input id="solution" type="button" value="Show solution">
</div>
var textarea = document.getElementById('code');
var reset = document.getElementById('reset');
var solution = document.getElementById('solution');
var code = textarea.value;
var userEntry = textarea.value;
function updateCode() {
eval(textarea.value);
}
reset.addEventListener('click', function() {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = jsSolution;
solution.value = 'Show solution';
updateCode();
});
solution.addEventListener('click', function() {
if(solution.value === 'Show solution') {
textarea.value = solutionEntry;
solution.value = 'Hide solution';
} else {
textarea.value = userEntry;
solution.value = 'Show solution';
}
updateCode();
});
var jsSolution = 'var list = document.querySelector(\'.output ul\');\nvar totalBox = document.querySelector(\'.output p\');\nvar total = 0;\nlist.innerHTML = \'\';\ntotalBox.textContent = \'\';\n\nvar products = [\'Underpants:6.99\',\n \'Socks:5.99\',\n \'T-shirt:14.99\',\n \'Trousers:31.99\',\n \'Shoes:23.99\'];\n\nfor(var i = 0; i < products.length; i++) {\n var subArray = products[i].split(\':\');\n var name = subArray[0];\n var price = Number(subArray[1]);\n total += price;\n itemText = name + \' — $\' + price;\n\n var listItem = document.createElement(\'li\');\n listItem.textContent = itemText;\n list.appendChild(listItem);\n}\n\ntotalBox.textContent = \'Total: $\' + total.toFixed(2);';
var solutionEntry = jsSolution;
textarea.addEventListener('input', updateCode);
window.addEventListener('load', updateCode);
// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead
textarea.onkeydown = function(e){
if (e.keyCode === 9) {
e.preventDefault();
insertAtCaret('\t');
}
if (e.keyCode === 27) {
textarea.blur();
}
};
function insertAtCaret(text) {
var scrollPos = textarea.scrollTop;
var caretPos = textarea.selectionStart;
var front = (textarea.value).substring(0, caretPos);
var back = (textarea.value).substring(textarea.selectionEnd, textarea.value.length);
textarea.value = front + text + back;
caretPos = caretPos + text.length;
textarea.selectionStart = caretPos;
textarea.selectionEnd = caretPos;
textarea.focus();
textarea.scrollTop = scrollPos;
}
// Update the saved userCode every time the user updates the text area code
textarea.onkeyup = function(){
// We only want to save the state when the user code is being shown,
// not the solution, so that solution is not saved over the user code
if(solution.value === 'Show solution') {
userEntry = textarea.value;
} else {
solutionEntry = textarea.value;
}
updateCode();
};
html {
font-family: sans-serif;
}
h2 {
font-size: 16px;
}
.a11y-label {
margin: 0;
text-align: right;
font-size: 0.7rem;
width: 98%;
}
body {
margin: 10px;
background-color: #f5f9fa;
}
{{ EmbedLiveSample('Playable_code', '100%', 730, "", "", "hide-codepen-jsfiddle") }}
A good use for array methods like {{jsxref("Array.prototype.push()","push()")}} and {{jsxref("Array.prototype.pop()","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:
// 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.<h2>Live output</h2>
<div class="output" style="min-height: 150px;">
<input type="text"><button>Search</button>
<ul>
</ul>
</div>
<h2>Editable code</h2>
<p class="a11y-label">Press Esc to move focus away from the code area (Tab inserts a tab character).</p>
<textarea id="code" class="playable-code" style="height: 370px; width: 95%">
var list = document.querySelector('.output ul');
var searchInput = document.querySelector('.output input');
var searchBtn = document.querySelector('.output button');
list.innerHTML = '';
var myHistory = [];
searchBtn.onclick = function() {
// we will only allow a term to be entered if the search input isn't empty
if (searchInput.value !== '') {
// number 1
// empty the list so that we don't display duplicate entries
// the display is regenerated every time a search term is entered.
list.innerHTML = '';
// loop through the array, and display all the search terms in the list
for (var i = 0; i < myHistory.length; i++) {
itemText = myHistory[i];
var listItem = document.createElement('li');
listItem.textContent = itemText;
list.appendChild(listItem);
}
// If the array length is 5 or more, remove the oldest search term
if (myHistory.length >= 5) {
// number 2
}
// empty the search input and focus it, ready for the next term to be entered
searchInput.value = '';
searchInput.focus();
}
}
</textarea>
<div class="playable-buttons">
<input id="reset" type="button" value="Reset">
<input id="solution" type="button" value="Show solution">
</div>
html {
font-family: sans-serif;
}
h2 {
font-size: 16px;
}
.a11y-label {
margin: 0;
text-align: right;
font-size: 0.7rem;
width: 98%;
}
body {
margin: 10px;
background: #f5f9fa;
}
var textarea = document.getElementById('code');
var reset = document.getElementById('reset');
var solution = document.getElementById('solution');
var code = textarea.value;
var userEntry = textarea.value;
function updateCode() {
eval(textarea.value);
}
reset.addEventListener('click', function() {
textarea.value = code;
userEntry = textarea.value;
solutionEntry = jsSolution;
solution.value = 'Show solution';
updateCode();
});
solution.addEventListener('click', function() {
if(solution.value === 'Show solution') {
textarea.value = solutionEntry;
solution.value = 'Hide solution';
} else {
textarea.value = userEntry;
solution.value = 'Show solution';
}
updateCode();
});
var jsSolution = 'var list = document.querySelector(\'.output ul\');\nvar searchInput = document.querySelector(\'.output input\');\nvar searchBtn = document.querySelector(\'.output button\');\n\nlist.innerHTML = \'\';\n\nvar myHistory= [];\n\nsearchBtn.onclick = function() {\n if(searchInput.value !== \'\') {\n myHistory.unshift(searchInput.value);\n\n list.innerHTML = \'\';\n\n for(var i = 0; i < myHistory.length; i++) {\n itemText = myHistory[i];\n var listItem = document.createElement(\'li\');\n listItem.textContent = itemText;\n list.appendChild(listItem);\n }\n\n if(myHistory.length >= 5) {\n myHistory.pop();\n }\n\n searchInput.value = \'\';\n searchInput.focus();\n }\n}';
var solutionEntry = jsSolution;
textarea.addEventListener('input', updateCode);
window.addEventListener('load', updateCode);
// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead
textarea.onkeydown = function(e){
if (e.keyCode === 9) {
e.preventDefault();
insertAtCaret('\t');
}
if (e.keyCode === 27) {
textarea.blur();
}
};
function insertAtCaret(text) {
var scrollPos = textarea.scrollTop;
var caretPos = textarea.selectionStart;
var front = (textarea.value).substring(0, caretPos);
var back = (textarea.value).substring(textarea.selectionEnd, textarea.value.length);
textarea.value = front + text + back;
caretPos = caretPos + text.length;
textarea.selectionStart = caretPos;
textarea.selectionEnd = caretPos;
textarea.focus();
textarea.scrollTop = scrollPos;
}
// Update the saved userCode every time the user updates the text area code
textarea.onkeyup = function(){
// We only want to save the state when the user code is being shown,
// not the solution, so that solution is not saved over the user code
if(solution.value === 'Show solution') {
userEntry = textarea.value;
} else {
solutionEntry = textarea.value;
}
updateCode();
};
{{ EmbedLiveSample('Playable_code_2', '100%', 700, "", "", "hide-codepen-jsfiddle") }}
위에 글 읽어보니, 배열이 꽤 유용해 보인다는거 알꺼임; JavaScript에서 배열은 겁나 많이 쓰인다. 배열의 모든 항목 마다 똑같은 작업을 수행하려고 루프(loop)를 돌리니까 같이 알아놓으면 개꿀. 다음 모듈(챕터)에서 루프(loop)에 관한 기초부터 알려줄꺼니까 쫄지 말고 달려. 갈 길이 멀다. 이 모듈은 이제 다 봤어!
이제 여기서 남은건 이 모듈의 평가뿐이야. 앞에 보여준 글(articles)을 얼마나 이해 했는지 테스트 할꺼임.
Array object reference page — for a detailed reference guide to the features discussed in this page, and many more.{{PreviousMenuNext("Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps/Silly_story_generator", "Learn/JavaScript/First_steps")}}