자바스크립트 배열 맵()
예
모든 요소 값의 제곱근을 사용하여 새 배열을 반환합니다.
const numbers = [4, 9, 16, 25];
const newArr = numbers.map(Math.sqrt)
배열의 모든 값에 10을 곱합니다.
const numbers = [65, 44, 12, 4];
const newArr = numbers.map(myFunction)
function myFunction(num) {
return num * 10;
}
아래에 더 많은 예가 있습니다.
정의 및 사용
map()
모든 배열 요소에 대한 함수를 호출하여 새 배열을 만듭니다.
map()
배열의 각 요소에 대해 한 번 함수를 호출합니다.
map()
빈 요소에 대해서는 함수를 실행하지 않습니다.
map()
원래 배열을 변경하지 않습니다.
통사론
array.map(function(currentValue, index, arr), thisValue)
매개변수
Parameter | Description |
function() | Required. A function to be run for each array element. |
currentValue | Required. The value of the current element. |
index | Optional. The index of the current element. |
arr | Optional. The array of the current element. |
thisValue | Optional. Default value undefined .A value passed to the function to be used as its this value. |
반환 값
유형 | 설명 |
배열 | 각 배열 요소에 대한 함수의 결과입니다. |
브라우저 지원
map()
ECMAScript5(ES5) 기능입니다.
모든 브라우저에서 완전히 지원되는 ES5(JavaScript 2009):
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |
더 많은 예
각 사람의 전체 이름을 얻으십시오.
const persons = [
{firstname : "Malcom", lastname: "Reynolds"},
{firstname : "Kaylee", lastname: "Frye"},
{firstname : "Jayne", lastname: "Cobb"}
];
persons.map(getFullName);
function getFullName(item) {
return [item.firstname,item.lastname].join(" ");
}