Array.from()은 매서드는 유사배열객체나 반복가능한객체를 얕게 복사해서 새로운 Array객체를 만든다고한다.
일단 무슨말인지 모르겠다. 그래서 배열 유사배열객체, 반복가능한객체가 무엇인지부터 알아보자.
배열은
let array = [1,2,3];
유사배열객체
let arrayLikeObject1= {
1 : a,
2 : b,
3 : c
}
let arrayLikeObject2 = document.querySelectorAll('div')
// NodeList [div, div, div, div, div, ...]
반복가능한객체는
반복가능한객체가 여러개 들어있고, 한번에 하나씩 꺼낼수있는객체라한다.
무슨말인지 모르겠다. _다음에 다시 알아보도록하자._
그래서 배열과 유사배열을 구분하는 이유는 유사배열의 경우 배열의 매서드를 사용할수없다고한다.
array.forEach(function(l) { console.log(l); }); // 1, 2, 3
arrayLikeObject2.forEach(function(li) { console.log(li); });
// Uncaught TypeError: els.forEach is not a function
따라서 유사배열에 배열매서드를 사용할려면 call, apply를 사용해야한다.
Array.prototype.forEach.call(arrayLikeObject2, function(el) { console.log(el); });
[].forEach.call(els, function(el) { console.log(el); });
어렵다. 하지만 더좋은방법이 생겼다.
Array.from(arrayLikeObject2).forEach(function(el) { console.log(el)});
이렇게 하면 유사배열에도 배열객체를 사용할수있다.