[JS] 유사 배열 객체(Array-like Objects)

KJA·2022년 8월 31일
0

유사 배열 객체란?

유사 배열 객체는 이름 그대로 배열과 유사한 객체를 말합니다. 배열처럼 보이지만 배열이 아닙니다. JS에서 querySelectorAll이나 document.body.children으로 엘리먼트를 가져오면 유사 배열 객체에 담겨서 옵니다.

유사 배열 객체는 마치 배열처럼 인덱스로 프로퍼티 값에 접근할 수 있고, length 프로퍼티를 갖는 객체를 말합니다.

예시

HTML

<div class="hero">Iron Man</div>
<div class="hero">Spider-Man</div>
<div class="hero">Captain America</div>

JS

const $hero = document.querySelectorAll('.hero');
console.log($hero);

결과

유사 배열 객체

위의 이미지가 유사 배열 객체입니다. 배열처럼 보이지만 사실 풀어보면 아래와 같이 됩니다.

{
  0: div.hero,
  1: div.hero,
  2: div.hero,
  length: 3,
}

즉 배열처럼 생긴 객체입니다. { 0: div.hero, 1: div.hero, 2: div.hero, length: 3}과 같은 모양을 가진 객체입니다.

유사 배열 객체와 일반 객체의 중요한 차이점이 있습니다. 바로 배열의 map, forEach, reduce와 같은 메서드를 사용할 수 없습니다. 사용하게 되면 아래의 이미지처럼 에러가 뜨게 됩니다.
유사 배열 객체에 배열 메서드 사용

유사 배열 객체에 배열 메서드를 사용하려면 Array.from() 메서드로 유사 배열 객체를 진짜 배열로 바꾸면 됩니다.

The Array.from() static method creates a new, shallow-copied Array instance from an iterable or array-like object.

Array.from() 사용

const $hero = document.querySelectorAll('.hero');
Array.from($hero).map(v => console.log(v));

Array.from()

Array.from() 정리
https://velog.io/@kimkyeonghye/JS-Array.from

0개의 댓글