유사 배열 객체을 모르고 있었다..

홍정민·2024년 8월 23일

프로젝트 개발 중, 핸들러 event의 form.child의 요소들을 배열 처리하려고 배열 메서드를 사용하는 순간 오류가 발생하는 것이다. 오류 내용을 찾아본 결과 새로운 개념을 발견했다.

내가 자바스크립트를 자주 사용하기 때문에 자신 있는 언어라고 생각 했는데, 바로 그걸 꺾어 버린 유사 배열 객체라는 개념이 등장했다.

유사 배열 객체

이름 그대로 배열과 유사하지만 배열이 아닌 객체이다.

사실 이런건 글로만 보면 알 수 없다. 실제로 어떠한 코드들이 유사 배열 객체인지 예시를 통해 알아보자.

종류

01. NodeList 객체

document.querySelectorAll()로 가져오는 객체 등이 있다.

const body = document.querySelectorAll('body');
console.log(body);        			// NodeList [body]
console.log(Array.isArray(body))	// false

02. HTMLCollection 객체

document.getElementsByClassName(), Element.children 등의 객체가 있다.

const child = document.body.children
console.log(child);					// HTMLCollection [...]
console.log(Array.isArray(child))	// false

03. String 객체

문자열 객체는 유사 배열 객체의 특징과 동일하다.

04. arguments 객체

ES6에서 Rest parameter(나머지 매개변수) 도입으로 argument 객체는 사용되지 않지만, argument 객체 또한 유사 배열 객체이다.

function example() {
  console.log(arguments);	// Arguments(3) [1, 2, 3, ...]
  console.log(Array.isArray(arguments));	// false
}
example(1, 2, 3);

05. 유사 배열 객체

직접 객체를 만들면 다음과 같은 코드가 유사 배열 객체이다.

const object = {
  0: 'Apple',
  1: 'Banana',
  2: 'Cherry',
  length: 3
};
console.log(Array.isArray(object)) // false

특징

유사 배열 객체는 인덱스로 접근이 가능하고 length 속성이 있지만, 배열 메서드를 사용할 수 없다.

그렇다면 어떻게 해야 할까?

해결 방법

유사 배열 객체를 Array.from() 함수를 통해 배열로 바꾸면 .map, .foreach, filter 등의 배열 메서드를 사용할 수 있게 된다.

const object = {
  0: 'Apple',
  1: 'Banana',
  2: 'Cherry',
  length: 3
};
const array = Array.from(object); 

console.log(array)	// (3) ['Apple', 'Banana', 'Cherry']

0개의 댓글