[ES6+] 배열(Array)과 Array.from(), Array.of()


Array.of()

엘리먼트 안에서 array를 만들어주는 메소드

const friends = Array.of("aaa","bbb","ccc","bbb");
console.log(friends);
//"aaa","bbb","ccc","bbb"

Array.from()

array-like object로 부터 array를 만드는 메소드

//html
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>

//js
const buttons = document.querySelectorAll("button");
console.log(buttons);
//NodeList(5)[button,button,....]

//만약 이 상태로 forEach문을 돌린다면
buttons.forEach(button => {
  button.addEventListener("click", () => console.log("i've been clicked") )
})
//forEach is not a function 이라는 에러가 뜰것이다. 왜냐면 buttons는 배열이 아니기 떄문이다

여기서 Array.from을 사용할 수 있다.

배열이 아닌 buttons를 forEach를 돌리니 에러가 뜨므로

buttons를 배열로 만들어주는것이다

Array.from에서 Array-like object(여기서는 buttons)를 불러오면

forEach가 활성화되면서 사용할 수 있다.

Array.from(buttons).forEach(button => {
  button.addEventListener("click", () => console.log("i've been clicked") )
})
//각각의 버튼을 누를때마다 i've been clicked 콘솔찍음

이게 굉장히 유용한게,

항상 모든게 배열로 만들어지면 좋겠지마는 그렇지 않을때도 있기 때문이다.

HTMLcollection으로 올때도 있고, 여튼 배열형태로 오지 않을때가 있는데

이때 Array.from()을 쓰면 굉장히 유용하겠군!!!!


니꼬가 Array,from을 모르는 사람은 이게 왜 안되는지 몇시간동안 고민할거라고 했는데…

나한테 하는말인줄알고 뜨끔했네….

array와 array-like의 차이를 몰라서 그렇다며…흑흑

그래.. 지금이라도 알았으니 다행이구나..






노마드코더의 ‘ES6의 정석’을 듣고 정리 =)




© 2018. by sora

Powered by sora