❗️[Array methods] Array.map(), Array.forEach()

Bas·2021년 3월 27일
0

array function 을 가장 많이 사용할 때는 callback함수로 사용할 때입니다.

map()

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

const arr = [1, 2, 3]
const arr1 = arr.map(x => x * x);

console.log(arr1); // [1, 4, 9];

위의 예시처럼 메서드는 배열 안에 있는 인자들에 각각 값들을 똑같이 적용시켜서 그 반환값으로 새로운 배열을 만들어줍니다.

array.map(callbackFunction(currenValue, index, array), thisArg)를 보면 map 구문은 callbackFunction, thisArg 두 개의 매개변수를 가집니다.

위의 예시에서는 x는 currentValue x * x는 thisArg 입니다.

  • callbackFunction
    currenValue : 처리할 현재 요소.
    index : 배열 내 현재 값의 인덱스.
    array : 현재 배열.
    thisArg : callbackFunction 내에서 this로 사용될 값.

forEach()

forEachfor대신 사용하는 '반복문'입니다.

map과 차이점은 forEach함수 자체가 return하는 것은 아무것도 없다는 것 입니다.
(* 그래도 중간에 멈추고 탈출하고 싶을 때 return을 쓰면 멈추기 가능함!)

let startWithNames = [];
let names = ['a', 'ab', 'cbb', 'ada'];


names.forEach(el => {   
  if (el.startsWith('a')) {     
    startWithNames.push(el);   
  } 
});

console.log(startWithNames); // [ "a", "ab", "ada"]
let hasC = false;
let arr = ['a', 'b', 'c', 'd'];

arr.forEach(el => {
  if (el === 'c') {
    hasC = true;
    return;        //-----> 반복문 탈출
  }
});

console.log(hasC); // true
profile
바스버거

0개의 댓글