JavaScript 메서드로 데이터 다루기(2. 배열 다루기)

Park, Jinyong·2020년 4월 9일
0

Code States - Pre Course

목록 보기
4/11

Achievement Goals

  • 메서드를 이용해 문자열과 숫자를 원하는 형태로 만들 수 있다.
  • 메서드를 이용해 배열과 객체를 구분할 수 있다.
  • 객체의 키 및 값의 존재 여부를 확인할 수 있다.
  • 배열의 앞/뒤에 element를 추가 또는 삭제할 수 있다.
  • 불변성의 의미를 이해하고, 어떤 메서드가 Mutable 혹은 Immutable한지 구분할 수 있다.
  • for 문을 대체하여, forEach, filter, map, reduce, slice 등의 메서드를 이용해 배열을 원하는 형태로 만들 수 있다.
  • 불변성을 유지하는 것이 왜 좋은지 이해할 수 있다.
  • 함수형 프로그래밍의 특징을 이해할 수 있다.
    • 함수를 인자로 넘기는 방법에 대해 이해할 수 있다.
    • 메서드의 인자로 익명 함수를 즉시 넘기는 방법에 대해 이해할 수 있다.
    • callback에 대해 이해할 수 있다.

배열 다루기

배열 판별하기

배열은 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 존재 여부 확인하기

indexOf, includes

배열 안에서 특정 element가 있는지 확인하고 싶을 때 사용한다.

  • arguments: 찾고자하는 element, (검색 시작 index)
  • return value: 일치하는 element의 index, 없으면 -1
    • includes 메서드는 true 혹은 false
const 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를 추가, 삭제하기

배열의 element가 많으면 console.log() 명령어로 관찰하기 불편하다. 그럴 땐, 배열을 더 시각적으로 나타내주는 console.table() 명령어가 유용하다.

아래 메서드는 모두 mutable하다. 호출하는 것만으로 원본을 변경한다.

push

배열의 맨 뒤에 element를 추가하고 싶을 때 사용한다.

  • arguments: 추가하고자 하는 elements. 여러 개를 추가할 수 있다.
  • return value: 추가한 후의 배열의 길이
const fruits = ['pear', 'strawberry', 'orange'];
console.log(fruits.push('apple', 'blueberry')); // 4
console.log(fruits); // ["pear", "strawberry", "orange", "apple", "blueberry"]

pop

배열의 맨 뒤의 element를 가져오거나 삭제하고 싶을 때 사용한다.

  • arguments: 없음
  • return value: 마지막 element
const fruits = ['pear', 'strawberry', 'orange'];
console.log(fruits.pop()); // 'orange'
console.log(fruits); // ["pear", "strawberry"]

unshift

배열의 맨 앞에 element를 추가하고 싶을 때 사용한다.

  • arguments: 추가하고자 하는 elements
  • return value: 추가한 후의 배열의 길이
const fruits = ['pear', 'strawberry', 'orange'];
console.log(fruits.unshift('grape')); // 4
console.log(fruits); // ["grape", "pear", "strawberry", "orange"]

shift

배열의 맨 앞의 element를 가져오거나 삭제하고 싶을 때 사용한다.

  • arguments: 없음
  • return value: 맨 앞의 element
const fruits = ['pear', 'strawberry', 'orange'];
console.log(fruits.shift()); // 'pear'
console.log(fruits); // ["strawberry", "orange"]

배열의 불변성(Immutability) 유지

위에서 말한 메서드들은 실행하는 순간 배열의 불변성을 깨버린다. 불변성을 유지하고 싶으면 원본을 복사하고 새로운 배열을 제어해야 한다. 이 때 복사하기 위해서 단순한 = 연산자는 원본 객체의 주소만을 복사해오는 것이기 때문에 원본에 영향을 미친다.

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 메서드는 문자열의 메서드처럼 배열의 일부분을 잘라서 가져올 수 있다.

  • arguments: 시작 index, 마지막 index
    • 마지막 index의 값은 포함하지 않는다.
    • 인수를 넣지 않으면 똑같은 배열을 반환한다.
    • 음수를 넣을 수 있다.
  • return value: 잘라낸 배열
const fruits = ['apple', 'blueberry', 'mango', 'grape', 'melon'];
const partialFruits = fruits.slice(1, 3); 
console.log(partialFruits); // ["blueberry", "mango"]

0개의 댓글