[Javascript] 유사 배열 객체 (Array-like Object)

유사 배열 객체

유사 배열 객체는 배열처럼 동작하지만 실제로는 배열이 아닌 객체이다. 유사 배열 객체는 숫자형 인덱스와 길이를 나타내는 length 속성이 있어서 배열과 유사하게 데이터를 저장하고 접근할 수 있다. 유사 배열 객체는 실제로 배열이 아니기 때문에 배열 메서드 push, pop, map 등을 직접 사용할 수 없지만 Array.prototype 의 메서드를 빌려오면 사용할 수 있다.

 

특징

  • length 속성은 데이터의 길이를 나타낸다.
  • 객체의 키가 숫자형으로 되어있어서 배열처럼 인덱스를 통해 데이터에 접근할 수 있다.
  • 배열 메서드를 사용할 수 없다.
  • 배열이 아니라 일반적인 객체로 처리된다. typeof 가 object 이다.

 

예시

유사 배열 객체 예시

const arrayLike = {
    0: "apple",
    1: "banana",
    2: "cherry",
    length: 3
};

console.log(arrayLike[0]); // "apple"
console.log(arrayLike.length); // 3

 

배열 메서드 사용 시

const arrayLike = {
    0: "apple",
    1: "banana",
    2: "cherry",
    length: 3
};

arrayLike.push("date"); // TypeError: arrayLike.push is not a function

 

배열 메서드 사용하는 방법

Array.propotype 의 메서드를 사용하면 배열처럼 동작할 수 있다.

const arrayLike = {
    0: "apple",
    1: "banana",
    2: "cherry",
    length: 3
};

// Array.prototype.slice를 이용해 배열로 변환
const realArray = Array.prototype.slice.call(arrayLike);
console.log(realArray); // ["apple", "banana", "cherry"]

// Array.prototype.map 사용
const upperCaseArray = Array.prototype.map.call(arrayLike, item => item.toUpperCase());
console.log(upperCaseArray); // ["APPLE", "BANANA", "CHERRY"]

 

유사 배열 객체 예

arguments 객체

자바스크립트 함수 내부에서 사용되는 arguments 객체는 유사 배열 객체이다.

function example() {
    console.log(arguments); // 유사 배열 객체
    console.log(arguments[0]); // 첫 번째 인자
    console.log(arguments.length); // 인자의 개수
}

example("apple", "banana", "cherry");

 

DOM

NodeList 등 DOM 관련 메서드들이 반환하는 객체도 유사 배열 객체이다.

const nodeList = document.querySelectorAll("div");
console.log(nodeList); // NodeList, 유사 배열 객체
console.log(nodeList[0]); // 첫 번째 div 요소
console.log(nodeList.length); // div 요소의 개수