자바스크립트에서 배열.map() 사용해 클래스 배열 만들고 싶을 때 에러

발생 에러

자바스크립트에서 map() 메서드를 사용해서 새로운 클래스 배열을 만들고 싶을 때,
새로운 배열의 요소가 클래스가 아니라 undefined로 만들어지는 에러가 발생했다.

const classArr = arr.map(element => {
  ...
  new Class(element);
});

---
[undefined, undefined, undefined, undefined] // classArr


이유

map()도 함수인데 return 값으로 정의된게 없어서 undefined가 return되고 있었던 것이다.
map(element => {}) 에서 element를 가지고 중괄호 {} 안에서 여러 작업을 처리하고 싶으면 꼭 return키워드를 사용해서 return할 값을 적어줘야 한다.


해결 방법

return 키워드를 사용해 return할 값을 적어준다.

const classArr = arr.map(element => {
  ...
  return new Class(element);
});

Categories:

Updated:

Leave a comment