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

HyeLin·2022년 11월 8일
1
post-thumbnail

배열이 아닌데 배열인 척 하는 것들을.. 유사배열 혹은 유사배열객체 라고 한다

ex)

유사배열 객체는 이렇게 만들 수 있다.

let arr = {
  0:'I',
  1:'am',
  2:'hyelin',
  length: 3
}

⚡️ 반드시, length를 가져 와야한다. 매우 원시적인 방법이고, 바뀔때 마다 length를 갱신해줘야 한다. 가급적이면 유사배열을 만들지 않는 것이 좋다.


유사배열은 원타입이 Object이기 때문에, 배열 메소드를 사용할 수 없다.
그래서! 유사배열을 진짜 배열로 바꾸는 방법이 있다.

바로바로 🔥 Array.from 🔥

ex)

const buttons = document.querySelectorAll("button");
const arr = Array.from(buttons);

arr.forEach((button) => {
  button.addEventListener("click", () => console.log("a"));
});

Array.from ....유용 그 잡채 😍

profile
개발자

1개의 댓글

comment-user-thumbnail
2022년 11월 11일

유 --- 용

답글 달기