8.1 배열 생성하기
자바스크립트의 배열은 값의 정렬된 컬렉션을 저장할 수 있는 데이터 구조야. 이 값들은 숫자, 문자열, 객체, 다른 배열 등 어떤 타입도 될 수 있어. 자바스크립트의 배열은 동적으로 크기가 변할 수 있어서, 프로그램 실행 중에 크기가 변할 수 있거든.
배열을 생성하고 초기화하기:
1. 배열 리터럴 사용하기
배열을 생성하는 가장 간단한 방법은 대괄호 []를 사용하는 거야:
JavaScript
let array1 = []; // 빈 배열
let array2 = [1, 2, 3]; // 세 개의 요소가 있는 배열
2. 생성자 함수 Array 사용하기
Array 생성자를 사용하여 배열을 생성할 수 있어:
JavaScript
let array1 = new Array(); // 빈 배열
let array2 = new Array(3); // 길이가 3인 배열 (모든 요소가 undefined)
let array3 = new Array(1, 2, 3); // 세 개의 요소가 있는 배열
3. 배열에 값 채우기
생성 후 배열에 값을 채울 수 있어:
JavaScript
let array = [];
array[0] = 'apple';
array[1] = 'banana';
array[2] = 'cherry';
8.2 배열 요소에 접근하기
배열의 요소는 0부터 시작하는 인덱스를 사용해. 요소에 접근하려면 대괄호를 사용하면 돼:
JavaScript
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // "Apple"
console.log(fruits[1]); // "Banana"
console.log(fruits[2]); // "Cherry"
배열 요소 변경하기
인덱스를 사용하여 배열 요소를 변경할 수 있어:
JavaScript
let fruits = ["Apple", "Banana", "Cherry"];
fruits[1] = "Blueberry";
console.log(fruits); // ["Apple", "Blueberry", "Cherry"]
length 속성
length 속성은 배열 내의 요소 개수를 반환해:
JavaScript
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits.length); // 3
8.3 배열에 요소를 추가하고 제거하는 메서드
1. push 메서드
push() 메서드는 하나 이상의 요소를 배열의 끝에 추가하고 새 배열의 길이를 반환해:
JavaScript
let fruits = ['apple', 'banana'];
fruits.push('cherry'); // ['apple', 'banana', 'cherry']
console.log(fruits.length); // 3
2. pop 메서드
pop() 메서드는 마지막 요소를 배열에서 제거하고 그 요소를 반환해:
JavaScript
let fruits = ['apple', 'banana', 'cherry'];
let last = fruits.pop(); // 'cherry'
console.log(fruits); // ['apple', 'banana']
3. shift 메서드
shift() 메서드는 첫 번째 요소를 배열에서 제거하고 그 요소를 반환해. 나머지 요소들은 하나씩 왼쪽으로 이동해:
JavaScript
let fruits = ['apple', 'banana', 'cherry'];
let first = fruits.shift(); // 'apple'
console.log(fruits); // ['banana', 'cherry']
4. unshift 메서드
unshift() 메서드는 하나 이상의 요소를 배열의 시작에 추가하고 새 배열의 길이를 반환해:
JavaScript
let fruits = ['banana', 'cherry'];
fruits.unshift('apple'); // ['apple', 'banana', 'cherry']
console.log(fruits.length); // 3
GO TO FULL VERSION