ARRAY - Array.from() and Array.of()

KimsPractice·2022년 12월 7일
0

ES6의 정석

목록 보기
15/30
post-thumbnail

출처 : Nomadcoders ES6의정석

이번 섹션은 ES6에서 업데이트된 ARRAY관련 메서드들에 알아보자.

  1. Array.of()

Array.of()는 인자로 받은 값을 유형에 상관없이 배열을 만들어 반환한다.


//일반 배열 
const userList = ['kims','prac','tice']

const userList = Array.of('kims','prac','tice')
console.log(userList)

  1. Array.from()

Array.from()의 기능을 알아보려면 유사배열객체(Array like Object)라는걸 먼저 알아야한다.

우선 예시를 한번 보자.

//html엔 btn이라는 class명을 가진 button요소가 1~10까지 있다.
const btns = document.getElementsByClassName('btn')

console.log(btns)


위와 같이 인덱스를 가지며 배열처럼 생긴 오브젝트를 유사배열오브젝트라고 한다.

const btns = document.getElementsByClassName('btn')

btns.forEach(btn=>{
  btn.addEventListener('click',()=>{
    console.log("i cliked")
  })
})

그렇다면 위 코드를 실행하면 어떤 결과가 나올게 될까

배열처럼 생겼지만, 결국 배열이 아닌 오브젝트이기때문에 에러가 발생한다.
이럴때 사용하는것이 바로 Array.from()이다.

const btns = document.getElementsByClassName('btn')

const arr = Array.from(btns)
arr.forEach(btn=>{
  btn.addEventListener('click',()=>{
    console.log("i cliked")
  })
})

이처럼 Array.from()은 배열이 아닌 유사배열객체를 배열로 변환하여 반환한다.

profile
난 그냥 살아 아주잘살아

0개의 댓글