본문 바로가기

Study/JS

JS - Array.prototype.map() 구현하기

map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다. - mdn

 

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]

다음과 같이 배열의 요소 하나하나에 원하는 함수를 넣어서

그 결과로 새로운 배열을 만드는 map 함수를 직접 구현해보겠습니다.

 

 

const arr = [1,2,3,4,5];

먼저 임의의 배열을 먼저 추가해줍니다.

 

Array.prototype.map2 = function(callback) {
  return null;
}

현업에서는 map2 = () => { ... } 와 같이 함수를 생성하지만 저는 웹브라우저 콘솔에서

테스트를 할것이라 다음과 같이 임의의 함수(map2)를 생성했습니다.

 

Array.prototype.map2 = function(callback) {
    console.log(this);
  return null;
}

console.log(arr.map2())

map2 함수에서 arr에 접근하는 방법은 this를 사용하는 것입니다.

 

위 코드를 실행하면 다음과 같은 결과를 얻을 수 있습니다.

이제 arr에 접근하는 방법을 알았으니 코드를 작성해보겠습니다.

 

Array.prototype.map2 = function(callback) {
  const newArray = [];
  for(let i = 0; i < this.length; i++){
    const callbackItem = callback(this[i], i);
    newArray.push(callbackItem);
  }
  return newArray;
}

callback 의 첫번째 인자 e에 arr[index]와 두번째 인자 i에 index를 넣어주고,
요구하는 함수의 값을 newArray에 넣어주고 리턴해줬습니다.

'Study > JS' 카테고리의 다른 글

JS - 문자열에서 숫자 추출하기  (0) 2023.02.28
JS - 배열 순서 바꾸기  (0) 2023.01.31
JS - Array.prototype.filter() 구현하기  (0) 2022.11.02
JS - Array.prototype.reduce() 구현하기  (0) 2022.11.02
클로저 (Closure)  (0) 2022.10.05