유사 배열 객체와 배열의 차이

onezerokang·2021년 5월 27일
4

Javascript

목록 보기
2/7

유사 객체 배열(array-like objects)란 무엇이고 배열과 어떤 차이가 있는지 간단하게 알아보겠다.

정의

유사 객체 배열은 배열처럼 보이지만 사실 key가 숫자이고 length 값을 가지고 있는 객체를 말한다. JS에서 querySelectorAll이나 document.body.children으로 엘리먼트를 가져오면 유사 배열 객체에 담겨서 온다.

예시
HTML

<div class="text">Hello</div>
<div class="text">World</div>
<div class="text">I'm</div>
<div class="text">Programmer</div>

JavaScript

const texts = document.querySelectorAll('.text');
console.log(texts);

결과

저 놈이 유사 배열 객체이다. 배열처럼 보이지만 사실 풀어보면 아래와 같이 된다.

{
  0: div.text,
  1: div.text,
  2: div.text,
  3: div.text,
  length: 4,
}

즉 배열같이 생겼지만 사실 객체다... 해서 유사 배열 객체다. 근데 이 유사 배열 객체와 일반 객체의 중요한 차이가 있다. 바로 배별의 forEach, map, filter, reduce 같은 메서드를 사용할 수 없다는 것이다.

그러면 어떻게 해야 하는가? 바로 Array.from( )메서드를 사용하면 된다.

Array.from() 메서드는 유사 배열 객체(array-like object)나 반복 가능한 객체(iterable object)를 얕게 복사해새로운Array 객체를 만듭니다.(MDN)

Array.from()으로 유사 배열 객체이 있는 value를 복사해 배열로 만드는 것이다. 그러면 배열 메서드를 사용할 수 있다.

const texts = document.querySelectorAll('.text');
Array.from(texts).map((text) => console.log(text));

그러면 유사 배열 객체와 일반 배열의 차이 포스팅을 마치겠습니다.

출처
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/from
https://www.zerocho.com/category/JavaScript/post/5af6f9e707d77a001bb579d2

profile
블로그 이전 했습니다: https://techpedia.tistory.com

1개의 댓글

comment-user-thumbnail
2022년 4월 16일

querySelectorAll 로 반환된는 배열엔 forEach는 사용되고 map은 안 되더라구요.. 이상합니다

답글 달기