목차

Javascript Array map() Method

  • description : Javascript Array map() Method
  • author : 오션
  • email : shlim@repia.com
  • lastupdate : 2021-05-26


The source of this article

JavaScript Array map() Method

Example

기존 배열에 있는 모든 값의 제곱근을 가진 배열을 반환합니다.

<body>
 
  <p>Click the button to get the square root of each element in the array.</p>
 
  <button onclick="myFunction()">Try it</button>
 
  <p id="demo"></p>
 
  <script>
    var numbers = [4, 9, 16, 25];
 
    function myFunction() {
      x = document.getElementById("demo");
      x.innerHTML = numbers.map(Math.sqrt);
      console.log(numbers.map(Math.sqrt)); /* (4)[2, 3, 4, 5] */
    }
  </script>
</body>

Definition and Usage

map() 메서드는 모든 배열 요소에 대해 함수를 호출한 결과로 새 배열을 만듭니다.

map() 메서드는 배열의 각 요소에 대해 순서대로 제공된 함수를 한 번씩 호출합니다.

Note: map()은 값이 없는 배열 요소에 대해 함수를 실행하지 않습니다.

Note: 이 메서드는 기존 배열을 변경하지 않습니다.

Syntax

array.map(function(currentValue, index, arr), thisValue)

Parameter Values

Parameter Description
function ( currentValue, index, arr ) 필수입니다. 배열의 각 요소에 대해 실행될 함수입니다.
Argument Description
currentValue 필수입니다. 현재 요소의 값
index 선택 사항. 현재 요소의 배열 인덱스
arr 선택 사항. 현재 요소가 속한 배열 객체
thisValue 선택 사항. “this” 값으로 사용할 함수에 전달할 값입니다.
이 매개 변수가 비어 있으면, “undefined”값이 “this” 값으로 전달됩니다.


Technical Details

Return Value: 기존 배열에서 각 요소에 대해 제공된 함수를 호출한 결과를 포함하는 배열
JavaScript version: ECMAScript 5


More Examples

Example

배열의 모든 값에 10을 곱합니다.

<body>
 
  <p>Multiply every element in the array with 10:</p>
 
  <p id="demo"></p>
 
  <script>
    var numbers = [65, 44, 12, 4];
    var newarray = numbers.map(myFunction);
 
    function myFunction(num) {
      return num * 10;
    }
    document.getElementById("demo").innerHTML = newarray; // 650,440,120,40
  </script>
 
</body>

Example

배열에 있는 각각의 사람에 대한 풀 네임(full name)을 가져옵니다.

<body>
 
  <p>Click the button to get a new array with the full name of each person in the array.</p>
  <button onclick="myFunction()">Try it</button>
 
  <p>New array: <span id="demo"></span></p> <!-- Malcom Reynolds,Kaylee Frye,Jayne Cobb -->
 
  <script>
    var persons = [
      { firstname: " Malcom", lastname: "Reynolds" },
      { firstname: "Kaylee", lastname: "Frye" },
      { firstname: "Jayne", lastname: "Cobb" }
    ];
 
    function getFullName(item) {
      var fullname = [item.firstname, item.lastname].join(" ");
      return fullname;
    }
 
    function myFunction() {
      document.getElementById("demo").innerHTML =
        persons.map(getFullName);
    }
  </script>
 
</body>