Front-end

[JavaScript] 배열의 메소드 모음집 (Array's Method)

코소미 2021. 11. 26. 10:32

자바스크립트 - 배열의 메소드  (Array's Method)

indexOf  / lastIndexOf / includes / reverse

spread / splice / shift / pop / unshift / push


자바스크립트의 배열의 메소드에 대해 알아보자.
각 상황에 알맞은 메소드를 활용해서 개발하면 편리하다.

 

 

배열에서 특정 값 찾기 (indexOf / lastIndexOf)

배열에서 특정 값을 찾으려면 indexOf 메소드를 사용하면 된다.
 
array.indexOf(item)을 하면 array 배열에 item이 포함되어 있는지 확인할 수 있다.

  1. 만약 포함되어 있다면, item이 있는 인덱스가 리턴됩니다.
  2. 포함되어 있지 않다면, -1이 리턴됩니다.
  3. 여러 번 포함되어 있으면, 처음 발견된 인덱스가 리턴됩니다.
let brands = ['Google', 'Kakao', 'Naver', 'Kakao'];
console.log(brands.indexOf('Kakao'));
console.log(brands.indexOf('Daum'));
1
-1

 
그리고 비슷한 lastIndexOf 메소드가 있다.
indexOf와는 반대로 탐색을 에서 부터 한다. 즉, 방금과 같은 경우에 'Kakao'를 lastIndexOf 메소드로 찾게 되면 마지막에 있는 인덱스가 리턴이 된다.

let brands = ['Google', 'Kakao', 'Naver', 'Kakao'];
console.log(brands.lastIndexOf('Kakao'));
console.log(brands.lastIndexOf('Daum'));
3
-1

배열에서 특정 값이 있는지 확인하기 (includes)

indexOf/lastIndexOf 메소드는 특정 값을 찾아서 해당 값의 index를 알려준다.
그냥 그 값이 배열안에 있는지, 그 여부만 확인하고 싶을 때는 includes 메소드를 활용하면 된다.
 
array.includes(item)을 하게되면 array배열에 item이 있을 경우 true를, 없을 경우 false를 리턴합니다.

let brands = ['Google', 'Kakao', 'Naver', 'Kakao'];
console.log(brands.includes('Kakao'));
console.log(brands.includes('Daum'));
true
false

배열 뒤집기 (reverse)

reverse 메소드를 활용하면, 배열의 순서를 뒤집을 수도 있다.

let brands = ['Google', 'Kakao', 'Naver', 'Kakao'];
console.log(brands);
brands.reverse();
console.log(brands);
(4) ["Google", "Kakao", "Naver", "Kakao"]
(4) ["Kakao", "Naver", "Kakao", "Google"]

객체복사 또는 새로운 객체 만들기 (Spread)

Spread 구문은 배열을 다룰 때 유용하게 활용할 수 있다.
객체를 복사하거나 기존의 객체를 가지고 새로운 객체를 만들 때 Spread 구문 활용할 수가 있다.
 
 

객체 Spread하기

const vegetable = { 
  name: 'carrot', 
};

const vegetableClone = { 
  ...vegetable, // spread 문법!
};

console.log(vegetable);      // {name: "carrot"}
console.log(vegetableClone); // {name: "vegetable"}

중괄호 안에서 객체를 spread 하게되면, 해당 객체의 프로퍼티들이 펼쳐지면서 객체를 복사할 수가 있다.
 

const latte = {
  esspresso: '30ml',
  milk: '150ml'
};

const cafeMocha = {
  ...latte,
  chocolate: '20ml',
}

console.log(latte);     // {esspresso: "30ml", milk: "150ml"}
console.log(cafeMocha); // {esspresso: "30ml", milk: "150ml", chocolate: "20ml"}

다른 객체가 가진 프로퍼티에 다른 프로퍼티를 추가해서 새로운 객체를 만들 때 활용할 수 있다.
 
 
 
🚨 Spread로 새로운 배열을 만들거나, 함수의 아규먼트로 사용할 수는 없다. 🚨
 

const latte = {
  esspresso: '30ml',
  milk: '150ml'
};

const cafeMocha = {
  ...latte,
  chocolate: '20ml',
}

[...latte]; // Error

(function (...args) {
  for (const arg of args) {
    console.log(arg);
  }
})(...cafeMocha); // Error

 
객체를 spread할 때는 반드시 객체를 표현하는 중괄호 안에서 활용해야 한다 !


 

splice

 
Array.prototype.splice()
splice() 메서드는 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경합니다.

 

shift


Array.prototype.shift()
shift() 메서드는 배열에서 첫 번째 요소를 제거하고, 제거된 요소를 반환합니다. 
이 메서드는 배열의 길이를 변하게 합니다.
 
 
 
 
 
 
 
- 자바스크립트 Array에 대해 더 자세한 설명 
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array

Array - JavaScript | MDN

JavaScript Array 클래스는 리스트 형태의 고수준 객체인 배열을 생성할 때 사용하는 전역 객체입니다.

developer.mozilla.org

 
 
출처) 코드잇 Code it - 자바스크립트 기초 강의