javascript filter, forEach, map

Steve·2021년 3월 18일
0

배열에 대한 순회

forEach()

: array를 위한 대표적인 함수.기능은 for문과 동일. 배열안에 있는 값들에 대해 각각 함수를 실행

const numberList = [1,2,3];
numberList.forEach(number => console.log(number));

filter()

: 배열에서 특정 조건에 부합하는 원소들만 뽑아서 새로운 배열 생성
list에 있는 모든 item을 위한 함수 실행

const numberList = [0,1,2,3,4,5,6,7,8,9];
const filterList = numberList.filter(item => item > 5);
console.log(filterList); // [6,7,8,9]

map()

: 배열 안의 각 요소에 대해 일괄적으로 함수 실행

const numberList = [1,2,3];
console.log(numberList.map((item) => {
item*item;
}); // 1,4,9
const days = ['mon', 'tue', 'wed', 'thurs', 'fri'];
const addSmile = (day, index) => `${index+1} ${day}`;
const smilingDays = days.map(addSmile);

=> arrow function이 return을 함축하고 있다

const numberList = [1,2,3];
console.log(numberList.filter(kang => kang>=2 )); // 배열 안의 값 중 2이상 값들 출력

console.log(numberList.map(seong => seong*seong)); // 배열 안의 값 일괄 계산

numberList.forEach(seong => console.log(seong)); // 배열 안의 값들 각각에 대해 함수 시행

*map과 foreach의 차이
map은 새로운 배열을 리턴
foreach는 기존의 배열을 변경(리턴값을 안보냄)

// Example of forEach()
const arr = [1, 2, 3, 4, 5];
const mulArr = [];

arr.forEach(num => {
  mulArr.push(num * 3);
});

console.log(mulArr); // [3, 6, 9, 12, 15]
// Example of map()
const arr = [1, 2, 3, 4, 5];
const mulArr = arr.map(num => num * 3);

console.log(mulArr); // [3, 6, 9, 12, 15]
profile
Front-Dev

0개의 댓글