[TIL]자바스크립트 유사 객체와 배열

Calvin Park·2022년 7월 22일
0

유사 객체 배열은 Key가 숫자이고 length 값을 가지고 있는 객체이다.

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 같은 메서드를 직접적으로 사용할 수 없다는 것이다.
직접적으로 사용을할 수 없다?

let yoosaArray = {
  0: "a",
  1: "b",
  2: "c",
  3: "d",
  length: 4,
};
console.log(Array.isArray(yoosaArray));// false


els.forEach(function(el){
	console.log(el)
	})
//이렇게 직접적으로 사용을하면 에러가 나옵니다. 
//Uncaught TypeError: els.forEach is not a function

배열이 아니므로 생기는 에러.
이럴 때 메서드를 빌려 쓰는 방법이 있다. 배열 프로토타입에서 forEach메서드를 빌려오는 것

[].forEach.call(yoosaArray, function (el) {
  console.log(el);
});
//출력:
//a
//b
//c
//d

또는 최신 자바스크립트에서는 Array.from으로 더 간단하게 할 수 있다.

Array.from(yoosaArray).forEach(function (el) {
  console.log(el);
});
//출력:
//a
//b
//c
//d

[]<- 로 감싸져 있다고 다 같은 배열이 아니라는 것과, Array.isArray로 판별하는 방법, 배열 프로토타입에서 메서드를 빌려쓰는 방법에 대해서 알면 좋을듯 합니다.

p.s.

유사배열은 배열의 method인 push,pop,join,amp etc를 사용할 수 없습니다.

출처 링크

profile
Personal Velog Note

0개의 댓글