Array.prototype.map.call

Tony·2021년 9월 4일
0

javascript

목록 보기
28/61

drag and drop 관련 코드를 찾아보던 중 못 보던 메소드가 있어서 찾아보았다.

Array.prototype.map.call instead of Array.map.call

  • getElementsByClassName 또는 querySelectorAll은 Array가 아닌 NodeList를 return하기 때문에 Array의 method인 map을 사용할 수 없다.
// NodeList에선 사용할 수 없는 Array method, map
function enableDragSort(listClass) {
  const sortableLists = document.getElementsByClassName(listClass);

  sortableLists.map(list => enableDragList(list)); // 에러
  // Uncaught TypeError: sortableLists.map is not a function
}
  • 하지만 Array.prototype.map.call 사용해서 NodeList에서도 Array method를 사용할 수 있다.
// Array.prototype.map.call 사용 예
function enableDragSort(listClass) {
  const sortableLists = document.getElementsByClassName(listClass);

  Array.prototype.map.call(sortableLists, list => {
    enableDragList(list);
  });
}
  • 이 방법을 알기 전엔 for문을 사용했었다.
// Array.prototype.map.call 대신 for문으로도 대체가 가능하다.
function enableDragSort(listClass) {
  const sortableLists = document.getElementsByClassName(listClass);
  for (let i = 0; i < sortableLists.length; i++) {
    enableDragList(sortableLists[i]);
  }
}

결론

  • for문을 사용해도 상관 없지만 최소한 Array.prototype.map.call이 무엇을 의미하는지는 알아야 코드의 이해가 가능하다.
  • 코드를 이해해야 내가 원하는 대로 변경해서 적용할 수 있다.

참고 문헌

profile
움직이는 만큼 행복해진다

0개의 댓글