자바스크립트 배열(Javascript Array) 사용법: 기초부터 활용까지
안녕하세요! 오늘은 웹 개발의 필수 요소 중 하나인 자바스크립트(JavaScript)의 배열(Array)에 대해 알아보겠습니다. 배열은 여러 개의 데이터를 하나의 변수에 순서대로 저장하고 관리할 수 있게 해주는 강력한 자료구조입니다. 숫자, 문자열, 객체 등 다양한 타입의 데이터를 담을 수 있으며, 각 데이터는 고유한 인덱스(index)를 통해 접근할 수 있습니다.
1. 배열 생성하기: 두 가지 방법
자바스크립트에서 배열을 만드는 방법은 크게 두 가지가 있습니다.
배열 리터럴 (Array Literal):
[]
가장 흔하고 권장되는 방식입니다. 대괄호[]
안에 원하는 요소(element)들을 콤마(,)로 구분하여 넣어주면 됩니다.// 빈 배열 생성 let fruits = []; // 초기값을 가진 배열 생성 let colors = ["red", "green", "blue"]; // 다양한 타입의 데이터를 가진 배열 생성 let mixedArray = [1, "hello", true, null, { name: "John" }];
Array 생성자:
new Array()
new
키워드와 함께Array
생성자를 사용하는 방법입니다. 하지만 몇 가지 주의할 점이 있어 리터럴 방식이 더 선호됩니다.// 빈 배열 생성 let emptyArr = new Array(); // 초기값을 가진 배열 생성 let numbers = new Array(1, 2, 3, 4, 5); // 주의: 인자가 숫자 하나일 경우 let sizedArr = new Array(5); // [ , , , , ] -> 길이가 5이고 요소가 없는 배열 생성 console.log(sizedArr.length); // 5 console.log(sizedArr[0]); // undefined
new Array(5)
처럼 숫자 하나만 인자로 전달하면 해당 숫자를 요소로 갖는 배열이 아니라, 그 숫자만큼의 길이를 가진 빈 배열이 생성되므로 혼동하기 쉽습니다. 따라서 특별한 이유가 없다면 배열 리터럴[]
사용을 권장합니다.
2. 배열 요소에 접근하고 수정하기
배열에 저장된 각 데이터(요소)에는 인덱스를 통해 접근할 수 있습니다. 자바스크립트 배열의 인덱스는 0부터 시작합니다.
배열 길이 확인:
length
속성 배열에 몇 개의 요소가 들어있는지 알려줍니다.let animals = ["dog", "cat", "rabbit"]; console.log(animals.length); // 3
요소 접근:
배열이름[인덱스]
원하는 위치의 요소 값을 읽어올 수 있습니다.console.log(animals[0]); // "dog" (첫 번째 요소) console.log(animals[1]); // "cat" (두 번째 요소) // 마지막 요소 접근 console.log(animals[animals.length - 1]); // "rabbit" // 존재하지 않는 인덱스 접근 시 console.log(animals[3]); // undefined
요소 수정:
배열이름[인덱스] = 새로운값
특정 위치의 요소 값을 변경할 수 있습니다.animals[1] = "hamster"; // 두 번째 요소를 "hamster"로 변경 console.log(animals); // ["dog", "hamster", "rabbit"]
3. 배열에 요소 추가하기
배열의 끝이나 처음에 새로운 요소를 추가하는 방법입니다.
끝에 추가:
push()
메소드 가장 일반적인 방법으로, 배열의 마지막에 하나 이상의 요소를 추가하고 배열의 새로운 길이를 반환합니다.let fruits = ["apple", "banana"]; let newLength = fruits.push("orange", "grape"); console.log(fruits); // ["apple", "banana", "orange", "grape"] console.log(newLength); // 4
Tip:
배열이름[배열이름.length] = 새로운값;
방식으로도 끝에 추가할 수 있지만,push()
가 더 명확합니다.앞에 추가:
unshift()
메소드 배열의 맨 앞에 하나 이상의 요소를 추가하고 배열의 새로운 길이를 반환합니다.let fruits = ["apple", "banana"]; let newLength = fruits.unshift("strawberry"); console.log(fruits); // ["strawberry", "apple", "banana"] console.log(newLength); // 3
4. 배열에서 요소 제거하기
배열의 끝, 처음 또는 특정 위치의 요소를 제거할 수 있습니다.
끝에서 제거:
pop()
메소드 배열의 마지막 요소를 제거하고, 제거된 요소를 반환합니다. 배열의 길이는 1 줄어듭니다.let fruits = ["apple", "banana", "orange"]; let removedFruit = fruits.pop(); console.log(fruits); // ["apple", "banana"] console.log(removedFruit); // "orange"
앞에서 제거:
shift()
메소드 배열의 첫 번째 요소를 제거하고, 제거된 요소를 반환합니다. 배열의 길이는 1 줄어듭니다. (뒤따르는 요소들의 인덱스가 1씩 감소합니다.)let fruits = ["apple", "banana", "orange"]; let removedFruit = fruits.shift(); console.log(fruits); // ["banana", "orange"] console.log(removedFruit); // "apple"
특정 위치에서 제거/추가/교체:
splice()
메소드 매우 강력하고 유연한 메소드로, 특정 인덱스에서 요소를 제거하거나, 추가하거나, 교체할 수 있습니다. 원본 배열을 직접 수정합니다.배열.splice(시작인덱스, 제거할갯수[, 추가할요소1[, 추가할요소2[, ...]]])
let numbers = [10, 20, 30, 40, 50]; // 인덱스 2에서 1개 요소 제거 let removed = numbers.splice(2, 1); console.log(numbers); // [10, 20, 40, 50] console.log(removed); // [30] // 인덱스 1에서 2개 요소 제거하고, 그 자리에 25, 35 삽입 removed = numbers.splice(1, 2, 25, 35); console.log(numbers); // [10, 25, 35, 50] console.log(removed); // [20, 40] // 인덱스 3에서 0개 요소 제거하고 (즉, 제거 안함), 45 삽입 numbers.splice(3, 0, 45); console.log(numbers); // [10, 25, 35, 45, 50]
5. 배열 유용하게 다루기: 주요 메소드들
자바스크립트는 배열을 편리하게 다룰 수 있는 다양한 내장 메소드를 제공합니다. 몇 가지 유용한 메소드를 소개합니다.
concat()
: 여러 배열을 합쳐 새로운 배열을 만듭니다. (원본 배열 변경 안 함)let arr1 = [1, 2]; let arr2 = [3, 4]; let combined = arr1.concat(arr2, [5, 6]); // [1, 2, 3, 4, 5, 6]
slice()
: 배열의 일부를 복사하여 새로운 배열을 만듭니다. (원본 배열 변경 안 함)배열.slice(시작인덱스[, 끝인덱스])
(끝 인덱스는 포함하지 않음)let arr = [1, 2, 3, 4, 5]; let subArr = arr.slice(1, 4); // [2, 3, 4] (인덱스 1부터 4 전까지) let subArr2 = arr.slice(2); // [3, 4, 5] (인덱스 2부터 끝까지)
indexOf()
,lastIndexOf()
: 특정 요소의 인덱스를 찾습니다. 없으면 -1을 반환합니다.let arr = [10, 20, 30, 20]; console.log(arr.indexOf(20)); // 1 (앞에서부터 찾은 첫 번째 20의 인덱스) console.log(arr.lastIndexOf(20)); // 3 (뒤에서부터 찾은 첫 번째 20의 인덱스) console.log(arr.indexOf(50)); // -1 (찾는 요소가 없음)
includes()
: 배열이 특정 요소를 포함하는지 확인합니다. (true/false 반환)let arr = ["apple", "banana", "cherry"]; console.log(arr.includes("banana")); // true console.log(arr.includes("grape")); // false
forEach()
: 배열의 각 요소에 대해 주어진 함수를 실행합니다.let numbers = [1, 2, 3]; numbers.forEach(function(number, index) { console.log(`Index ${index}: ${number}`); }); // 출력: // Index 0: 1 // Index 1: 2 // Index 2: 3
map()
: 배열의 각 요소에 함수를 적용하여 새로운 배열을 생성합니다.let numbers = [1, 2, 3]; let doubled = numbers.map(function(number) { return number * 2; }); console.log(doubled); // [2, 4, 6]
filter()
: 주어진 함수의 조건을 만족하는 요소들로만 이루어진 새로운 배열을 생성합니다.let numbers = [1, 2, 3, 4, 5]; let evenNumbers = numbers.filter(function(number) { return number % 2 === 0; }); console.log(evenNumbers); // [2, 4]
join()
: 배열의 모든 요소를 연결하여 하나의 문자열로 만듭니다. 구분자를 지정할 수 있습니다.let words = ["Hello", "World", "!"]; console.log(words.join(" ")); // "Hello World !" console.log(words.join("-")); // "Hello-World-!" console.log(words.join("")); // "HelloWorld!"
마무리
자바스크립트 배열은 데이터를 효율적으로 관리하고 다양한 작업을 수행할 수 있는 필수적인 도구입니다. 오늘 살펴본 생성, 접근, 수정, 추가, 제거 방법과 유용한 메소드들을 잘 익혀두시면 훨씬 강력하고 유연한 코드를 작성하실 수 있을 것입니다. 직접 코드를 작성하고 실행해보면서 배열과 친숙해지는 것이 중요합니다. Happy coding!