Array.map( ), Array.forEach( )

이예린·2020년 10월 4일
0

웹린이 탈출기

목록 보기
6/9

Array.map()

map() method는 array를 return 합니다. return된 배열은 array의 각 요소에 대하여 callback 함수가 return한 값 입니다.

callback 함수 선언 생략

const arr = [7, 1, 9, 13];

const mapArr = arr.map(x => x * 2);

console.log(mapArr);
// expected output: Array [14, 2, 18, 26]

callback 함수 선언

const arr = [7, 1, 9, 13];

const mapArr = arr.map(function (x) { 
  return x * 2;
});

console.log(mapArr);
// expected output: Array [14, 2, 18, 26]

Array.forEach( )

Array.forEach( ) method는 array 각 요소에 대하여 callback 함수를 실행 합니다. 인자가 1개 일 때에는 요소값을 사용할 수 있고, 인자가 2개 일 때에는 요소값과 index값을 사용할 수 있습니다.

인자 1개

const arr = ['a', 'b', 'c'];

arr.forEach(element => console.log(element));

// expected output: a
// expected output: b
// expected output: c

인자 2개

const arr = ['a', 'b', 'c'];

arr.forEach((element,index) => console.log(element,index));

// expected output: a0
// expected output: b1
// expected output: c2

0개의 댓글