- 배열 안에 있는 모든 요소를 호출해서 새로운 값을 반환하는 것.
MDN 설명 페이지
map()
메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.
const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]
설명 페이지 내용 확인
array1.map(x);라고 하면
1, 4, 9, 16
라는 결과가 나옴.
위에 예제의 코드는 () 안에 함수를 넣어서
function x() {
return x = x * 2
};
//화살표 함수로 바꾸면
//x => x*2;
- 전체 배열의 값을 2배로 반환하는 것을 보여줌.
다른 예제>
class Student {
constructor(name, age, enrolled, score) {
this.name = name;
this.age = age;
this.enrolled = enrolled;
this.score = score;
}
}
const students = [
new Student('A', 29, true, 45),
new Student('B', 28, false, 80),
new Student('C', 30, true, 90),
new Student('D', 40, false, 66),
new Student('E', 18, true, 88),
];
아래 클래스에서 나잇값만 뽑아서 배열로 배출하려면.
const studentAge = students.map(student => student.age);
이렇게 하면 나이만 배열로 출력됨.
studentAge = [29, 28, 30, 40, 18]
Comments