본문 바로가기
JavaScript

[javascript] Array.from으로 유사배열을 배열로 변환하기

by teamnova 2023. 9. 13.

안녕하세요! 오늘은 Array.from을 알아보고 예제를 통해 유사배열을 배열로 변환하고 클릭 리스너를 등록해보겠습니다. 

 

Array.from을 알아봅시다.

 

1. Array.from?

1. Array.from() :
유사 배열 객체(array-like object)나 반복 가능한 객체(iterable object)를 얕게 복사해 새로운 Array 객체를 만들어 반환한다.
-출처:https://developer.mozilla.org/-

2. Array.from 문법.

Array.from(arrayLike[, mapFn[, thisArg]])

(파라미터 설명)

arrayLike: 배열로 변환하고자 하는유사 배열 객체나 반복 가능한 객체.

mapFnOptional (선택) : 배열의 모든 요소에 대해 호출할 맵핑 함수. 
해당 파라미터는 각 요소를 맵핑 할 때 사용할 수 있다. 즉, Array.from(obj, mapFn, thisArg) 는 중간에 다른 배열을 생성하지 않는다는 점을 제외하면 Array.from(obj).map(mapFn, thisArg) 와 동일하다.

ex)  console.log(Array.from([1, 2, 3], x => x + x)); // Expected output: Array [2, 4, 6]

thisArg (선택) : 실행 시에 this로 사용할 값.

(추가 설명) 

다음과 같은 경우에 Array.from()으로새Array를 만들 수 있습니다.

1. 유사 배열 객체 (HTML Collection과 같이 length 속성과 인덱싱 된 요소를 가진 객체- array-like object) 
2. 순회 가능한 객체 (Map, Set 등객체의 요소를 얻을 수 있는 객체 - iterable object)

 

3. 언제 필요한 것인가? 

 

위에서 서술한 것처럼 유사배열은 배열처럼 보이지만, 배열의 메서드를 사용할 수 없습니다. forEach도 그 중 하나로, 배열이 아닌 유사배열에 배열 메서드를 사용하려고하면 아래와 같은 에러가 발생합니다.

Note: Uncaught TypeError: children.forEach is not a function

이 때 Array.from으로 iterable 객체 또는 유사배열(array-like object)를 array로 변환해서 그 값을 반환 시켜 배열 메서드를 적용하여 작업을 할 수 있습니다.

 

4. 예시

 

test.html

<button class="ex">1</button>
<button class="ex">2</button>
<button class="ex">3</button>
<button class="ex">4</button>
<button class="ex">5</button>

버튼이 여러개 있을 때 각 버튼에 이벤트 리스너를 하나씩 달아보려고 합니다.

 

test1.js

//클래스 이름으로 버튼들 가져오기
const buttons = document.getElementsByClassName('ex');

//forEach로 순회하여 각 버튼에 이벤트 클릭 리스너 설정
buttons.forEach(button => {
    //클릭 시 alert로 클릭 된 button의 textContet(숫자) 띄우기
    button.addEventListener("click",() => alert(button.textContent));
});

 

Array.from을 사용하지않았을 때입니다. 이 때 코드를 실행하면 이런 오류가 발생한 것을 확인할 수 있습니다.

 

 

buttons를 콘솔창에 출력하니 HTML collection이라고 뜹니다. HTML collection은 유사배열이기 때문에 forEach 메서드를 사용할 수 없어 발생한 오류입니다.

 

 

이제 Array.from으로 buttons를 배열로 변환하여 다시 forEach로 순회하며 클릭 리스너를 등록해보겠습니다. 

 

test2.js

// 클래스 이름으로 버튼들 가져오기
const buttons = document.getElementsByClassName('ex');

// HTMLCollection을 배열로 변환하여 forEach로 순회 
Array.from(buttons).forEach(button => {
    // 클릭 시 alert로 클릭된 button의 textContent(숫자) 띄우기
    button.addEventListener("click", () => alert(button.textContent));
});

 

아래는 test2.js를 적용했을 때 볼 수있는 결과 화면입니다.

 

이제 잘 작동하는 것을 확인 할 수 있습니다.

 

 

+ 자세한 내용은 아래 링크 참고 부탁드립니다.) 

https://2ality.com/2013/05/quirk-array-like-objects.html

 

JavaScript quirk 8: array-like objects

JavaScript quirk 8: array-like objects (Ad, please don’t block) [This post is part of a series on JavaScript quirks.] Some objects in JavaScript look like arrays, but aren’t. They are called array-like. This blog post looks at what exactly that means a

2ality.com

Indexed collections - JavaScript | MDN (mozilla.org)

 

Indexed collections - JavaScript | MDN

This chapter introduces collections of data which are ordered by an index value. This includes arrays and array-like constructs such as Array objects and TypedArray objects.

developer.mozilla.org

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/from

 

Array.from() - JavaScript | MDN

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

developer.mozilla.org

Array vs Array-Like Objects in JavaScript – Learn the Difference | CodeSweetly

 

Array vs Array-Like Objects in JavaScript – Learn the Difference | CodeSweetly

An array-like object does not have built-in methods like map(), pop(), and forEach(). However, a regular array has those methods.

codesweetly.com