배열은 typeof 명령어로 object가 나온다.
console.log(typeof [1,2,3]); // 'object'
아래와 같은 방법으로 배열을 판별할 수 있다.
console.log(Array.isArray([1,2,3])); // true
console.log(Array.isArray({key:'value'})); // false
배열 안에서 특정 element가 있는지 확인하고 싶을 때 사용한다.
includes 메서드는 true 혹은 falseconst fruits = ['pear', 'strawberry', 'orange'];
console.log(fruits.indexOf('pear')); // 0
console.log(fruits.indexOf('banana')); // -1
console.log(fruits.includes('strawberry')); // true
console.log(fruits.includes('apple')); // false
배열의 element가 많으면 console.log() 명령어로 관찰하기 불편하다. 그럴 땐, 배열을 더 시각적으로 나타내주는 console.table() 명령어가 유용하다.
아래 메서드는 모두 mutable하다. 호출하는 것만으로 원본을 변경한다.
배열의 맨 뒤에 element를 추가하고 싶을 때 사용한다.
const fruits = ['pear', 'strawberry', 'orange'];
console.log(fruits.push('apple', 'blueberry')); // 4
console.log(fruits); // ["pear", "strawberry", "orange", "apple", "blueberry"]
배열의 맨 뒤의 element를 가져오거나 삭제하고 싶을 때 사용한다.
const fruits = ['pear', 'strawberry', 'orange'];
console.log(fruits.pop()); // 'orange'
console.log(fruits); // ["pear", "strawberry"]
배열의 맨 앞에 element를 추가하고 싶을 때 사용한다.
const fruits = ['pear', 'strawberry', 'orange'];
console.log(fruits.unshift('grape')); // 4
console.log(fruits); // ["grape", "pear", "strawberry", "orange"]
배열의 맨 앞의 element를 가져오거나 삭제하고 싶을 때 사용한다.
const fruits = ['pear', 'strawberry', 'orange'];
console.log(fruits.shift()); // 'pear'
console.log(fruits); // ["strawberry", "orange"]
위에서 말한 메서드들은 실행하는 순간 배열의 불변성을 깨버린다. 불변성을 유지하고 싶으면 원본을 복사하고 새로운 배열을 제어해야 한다. 이 때 복사하기 위해서 단순한 = 연산자는 원본 객체의 주소만을 복사해오는 것이기 때문에 원본에 영향을 미친다.
const fruits = ['mango', 'grape', 'melon'];
const copiedFruits = fruits;
copiedFruits.pop();
console.log(fruits); // ["mango", "grape"]
그러므로, 배열의 값 자체를 복사해야 한다. 그 방법으로는 for 문을 사용할 수 있다.
const copiedFruits = [];
for (let i = 0; i < fruits.length; ++i) {
copiedFruits.push(fruits[i]);
}
console.log(copiedFruits); // ["mango", "grape", "melon"]
copiedFruits.pop();
console.log(copiedFruits); // ["mango", "grape"]
console.log(fruits); // ["mango", "grape", "melon"]
더 간단한 방법으로 slice 메서드를 사용하면 된다.
const copiedFruits = fruits.slice();
console.log(copiedFruits); // ["mango", "grape", "melon"]
copiedFruits.pop();
console.log(copiedFruits); // ["mango", "grape"]
console.log(fruits); // ["mango", "grape", "melon"]
slice 메서드는 문자열의 메서드처럼 배열의 일부분을 잘라서 가져올 수 있다.
const fruits = ['apple', 'blueberry', 'mango', 'grape', 'melon'];
const partialFruits = fruits.slice(1, 3);
console.log(partialFruits); // ["blueberry", "mango"]