Array.prototype.map()

신승준·2022년 6월 22일
0

Syntax

arr.map(callback(currentValue[, index[, array]])[, thisArg])

배열 내의 요소들을 순회하며, 각 요소마다 함수를 적용시킨 값을 요소로 하는 새로운 배열을 반환한다.

프로그래머스 - 자연수 뒤집어 배열로 만들기

function solution(n) {
    let result = String(n); // n + ''
    result = result.split('');
    result = result.reverse();
    result = result.map((i) => Number(i));
    
    return result;
}

문자열의 배열이 숫자의 배열로 바뀌었다.

프로그래머스 - 이상한 문자 만들기

function solution(s) {
    let words = s.split(' ');
    let result = Array();
    
    for (let i = 0; i < words.length; i++) {
        result.push(words[i].split('').map((current, j) => j % 2 ? current.toLowerCase() : current.toUpperCase()).join(''));
    }
    
    return result.join(' ');
}

인자

{title.map(function (element, index) {
    return (
        <div className="list">
            <h4>{title[index]}</h4>
            <p>{date}</p>
        </div>
    );
})}
  • map안의 콜백 함수 function에 2번째 인자는, 0부터 title의 요소를 순회할 때마다 1씩 증가한다. 즉 각 순회마다 title의 index라고 보면 된다.
profile
메타몽 닮음 :) email: alohajune22@gmail.com

0개의 댓글