08_배열(array)

Onew·2025년 9월 26일
0

js

목록 보기
13/24

1. 배열(Array)

1_1) 배열이란?

💡

배열은 여러 개의 값을 순차적으로 나열한 자료 구조이다.

  • 요소의 자료형은 제약이 없다.
  • array 타입은 별도로 없으며 배열은 object(객체) 타입에 해당한다.

1_2) 배열 생성

  • 배열 리터털
    const arr = ['바나나', '복숭아', '키위'];
  • 배열 생성자 함수
    const arr2 = new Array();
    const arr3 = new Array(10);
    const arr4 = new Array(1, 2, 3);
    • 전달 된 인수가 없을 경우 빈 배열을 생성한다.
    • 전달 된 인수가 1개이고 숫자인 경우 length 프로퍼티 값이 인수인 배열을 생성한다.
    • 전달 된 인수가 2개 이상이거나 숫자가 아닌 경우 인수를 요소로 갖는 배열을 생성한다.
  • Array.of 메소드
    const arr5 = Array.of(10);
    const arr6 = Array.of(1, 2, 3);
    const arr7 = Array.of("hello", "js");
    • 전달 된 인수를 요소로 갖는 배열을 생성한다.

1_3) 배열 요소 접근

  • 각 요소는 자신의 위치를 나타내는 index를 가진다 숫자는 0부터 시작한다.
  • 요소에 접근 시에는 대괄호 표기법을 사용한다
const arr = ['바나나', '복숭아', '키위'];

console.log(arr[0]);  // 바나나
console.log(arr[1]);  // 복숭아
console.log(arr[2]);  // 키위

1_4) length 속성

  • length
    • 배열에 담긴 요소의 개수를 확인할 수 있다.

      const arr = ['바나나', '복숭아', '키위'];
      
      console.log(arr.length);  // 3
    • 배열에 요소를 추가하거나 삭제하면 자동으로 갱신 된다.


2. 배열의 주요 메서드

  • push
    • 배열의 가장 뒷 부분에 요소를 추가할 때 사용한다.

    • 배열.push(요소)의 형태로 사용한다.

      const arr = ['바나나', '복숭아', '키위'];
      
      arr.push('딸기');
      
      console.log(arr);  // ['바나나', '복숭아', '키위', '딸기']
  • pop
    • 배열의 가장 뒷 부분의 요소를 제거할 때 사용한다.

    • 배열.pop()의 형태로 사용한다.

      const arr = ['바나나', '복숭아', '키위', '딸기'];
      
      arr.pop();
      
      console.log(arr);  // ['바나나', '복숭아', '키위']
  • unshift
    • 배열의 맨 앞에 요소를 추가한다.

    • 배열.unshift(요소)의 형태로 사용한다.

      const fruits = ['바나나', '오렌지'];
      
      fruits.unshift('사과');
      
      console.log(fruits); // ['사과', '바나나', '오렌지']
  • shift
    • 배열의 맨 앞 요소를 제거 후 반환한다.

      const fruits = ['사과', '바나나', '오렌지'];
      
      console.log(fruits.shift());  // 사과
      console.log(fruits);  // ['바나나', '오렌지']
  • slice
    • 배열.slice(인덱스, 제거할요소개수)의 형태로 사용한다.

    • 배열의 index 위치에 있는 요소를 선택해 잘라낸다.

      const animals = ['고양이', '강아지', '토끼', '햄스터', '거북이'];
      
      const removed = animals.slice(1, 2);
      console.log(removed);  // ['강아지']
      console.log(animals);  // ['고양이', '강아지', '토끼', '햄스터', '거북이']
  • splice
    • 배열.splice(인덱스, 제거할요소개수, 추가할 요소)의 형태로 사용한다.

    • 배열의 index 위치에 있는 요소를 선택해 제거하고 요소를 추가한다.

      const animals = ['고양이', '강아지', '토끼', '햄스터', '거북이'];
      
      animals.splice(2, 1, '새우');
      console.log(animals);  // ['고양이', '강아지', '새우', '햄스터', '거북이']
  • indexOf
    • 배열에서 요소가 위치한 index를 리턴 한다.

    • 없는 요소를 요청할 경우 -1이 나온다.

      const colors = ['빨강', '파랑', '노랑', '초록', '파랑'];
      
      console.log(colors.indexOf('파랑'));  // 1
      console.log(colors.indexOf('보라'));  // -1
    • 특정 인덱스부터 검색하는 것도 가능하다

      const colors = ['빨강', '파랑', '노랑', '초록', '파랑'];
      
      console.log(colors.indexOf('파랑', 2));  // 4
  • lastIndexOf
    • 배열의 요소가 위치한 마지막 index를 리턴 한다.

      const colors = ['빨강', '파랑', '노랑', '초록', '파랑'];
      
      console.log(colors.lastIndexOf('파랑'));  // 4
  • includes
    • 배열에 해당 요소가 존재 하는지 여부를 boolean 타입으로 리턴 한다.

      const colors = ['빨강', '파랑', '노랑', '초록', '파랑'];
      
      console.log(colors.includes('노랑'));  // true
      console.log(colors.includes('보라'));  // false
  • concat
    • 두 개 이상의 배열을 결합 한다.

      const fruits1 = ['사과', '바나나'];
      const fruits2 = ['오렌지', '포도'];
      const allFruits = fruits1.concat(fruits2);
      
      console.log(allFruits);  // ['사과', '바나나', '오렌지', '포도']
  • join
    • 배열을 구분자로 결합해 문자열로 반환한다.

      const fruits = ['사과', '바나나', '오렌지', '포도'];
      
      console.log(fruits.join());  // 사과,바나나,오렌지,포도
      
      console.log(fruits.join(' '));  // 사과 바나나 오렌지 포도
      console.log(fruits.join('-'));  // 사과-바나나-오렌지-포도
  • reverse
    • 배열의 순서를 뒤집는다.

      const numbers = [1, 2, 3, 4, 5];
      
      numbers.reverse();
      console.log(numbers);  // [5, 4, 3, 2, 1]
  • sort
    • 배열을 기준에 따라 정렬한다.

    • 오름차순 정렬이 기본이며, 정렬 후 정렬 순서를 유지한다.

    • 기본적으로 문자열 정렬이 된다.

    • 오름차순 / 내림차순 정렬할 때에는 다른 방식으로 전달해야 한다.
      - 오름차순 : numbers.sort((a, b) ⇒ a -b)
      - 내림차순 : numbers.sort((a, b) ⇒ b - a)

      const numbers = [10, 5, 40, 25, 1000, 1];
      
      numbers.sort();
      console.log(numbers);  // [1, 10, 1000, 25, 40, 5]
  • forEach
    • 배열의 각 요소를 반복하며 모든 요소에 대해 콜백 함수를 호출한다.

    • arr.forEach(callback(item[, index[, array]])) 형태로 사용한다.
      - item : 처리할 배열의 요소
      - index : 처리할 배열 요소의 인덱스
      - array : forEach를 호출한 배열

      const fruits = ['사과', '바나나', '오렌지'];
      
      fruits.forEach(fruit => {
        console.log(fruit);
      });
  • map

    • 각 요소를 변환 해서 새로운 배열을 만드는 메서드이다.

    • forEach의 동작 원리와 같지만 forEach와는 다르게 새로운 배열을 반환 한다.

      const numbers = [1, 2, 3, 4, 5];
      const doubled = numbers.map(num => num * 2);
      
      console.log(doubled);  // [2, 4, 6, 8, 10]
  • 콜백 함수란 (Callback function)

    • 다른 함수에 인자로 전달되는 함수이다.

    • 외부 함수 내에 호출되어 특정 작업을 진행 한다.

      function sayHello() {
          console.log('안녕하세요!');
        }
        
        function sayBye() {
          console.log('안녕히가세요!');
        }
        
        function greet(callback) {
          console.log('인사를 시작합니다.');
          callback();
          console.log('인사가 끝났습니다.');
        }
        
        greet(sayHello);
    • 콜백 함수는 왜 사용하는 걸까?
      1. 함수의 재사용성 측면에서 효율적이다
        • 함수를 호출하는 코드에서 동작을 자유롭게 변경할 수 있다
      2. 비동기적 처리 가능
        • 콜백 함수를 인자로 받아 시간이 지난 후에 실행되도록 할 수 있는데, 이 때 비동기적으로 콜백 함수를 실행하므로 다른 코드의 실행을 방해 하지 않는다
  • filter
    • 조건에 맞는 요소로만 구성된 새로운 배열을 반환한다.

      const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
      const evenNumbers = numbers.filter(num => num % 2 === 0);
      
      console.log(evenNumbers);  // [2, 4, 6, 8, 10]
  • reduce
    • 배열에 콜백 함수를 실행해 누적된 하나의 결과 값을 반환한다.

    • array.reduce(<콜백 함수>, <초기값>);

      const numbers = [1, 2, 3, 4, 5];
      const sum = numbers.reduce((acc, num) => acc + num, 0);
      
      console.log(sum);  // 15
  • some
    • 조건을 만족하는 요소가 하나라도 있으면 true를 반환한다.

    • boolean 타입의 값만 반환 한다.

      const numbers = [1, 3, 5, 7, 8];
      const hasEven = numbers.some(num => num % 2 === 0);
      
      console.log(hasEven);  // true
  • every
    • 배열의 모든 요소가 조건을 만족 하면 true를 반환한다.

    • 하나라도 통과하지 못 하면 false를 반환 후 중지한다.

    • boolean 타입의 값만 반환한다.

    • 빈 배열은 항상 true를 반환한다.

      const numbers = [1, 3, 5, 7, 9];
      const allPositive = numbers.every(num => num > 0);
      
      console.log(allPositive);  // true
  • find
    • 조건을 만족하는 첫 번째 요소를 반환 후 중지한다.

      const numbers = [1, 3, 5, 8, 9, 12];
      const firstEven = numbers.find(num => num % 2 === 0);
      
      console.log(firstEven);  // 8
  • findIndex
    • 조건을 만족하는 첫 번째 요소의 인덱스를 반환 후 중지한다.

    • 찾는 요소가 없으면 -1을 반환한다.

      const numbers = [1, 3, 5, 8, 9, 12];
      const firstEvenIndex = numbers.findIndex(num => num % 2 === 0);
      
      console.log(firstEvenIndex);  // 3

0개의 댓글