forEach 함수와 map 함수

SUN·2023년 3월 9일

JS 함수

목록 보기
2/8

1. forEach 설명

배열에서 사용하는 반복문으로 for문보다 간결하게 사용이 가능하다.
배열의 처음부터 마지막까지 반복실행하며 인자로 콜백함수를 받아 온다.

그러나 break, continue, return을 사용한 루프제어가 불가능하다.
for문과 다르게 함수, 메서드이기 때문에 루프제어가 불가

2. 구문

arr.forEach(callback(currentvalue[, index[, array]])[, thisArg])

currentValue : 처리할 현재요소
index : 처리할 현재 요소의 index
array : foreach를 호출할 배열
thisArg : 콜백을 실행할 때 this로 사용할 값

예시

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

arr.forEach(function(element, index, array){
    console.log(`${array}의 ${index}번째 요소 : ${element}`);
});

0,1,2,3,4,5,6,7,8,9,10의 0번째 요소 : 0
0,1,2,3,4,5,6,7,8,9,10의 1번째 요소 : 1
0,1,2,3,4,5,6,7,8,9,10의 2번째 요소 : 2
0,1,2,3,4,5,6,7,8,9,10의 3번째 요소 : 3
0,1,2,3,4,5,6,7,8,9,10의 4번째 요소 : 4
0,1,2,3,4,5,6,7,8,9,10의 5번째 요소 : 5

3. 예제

1. 단순 사용

const aaa = [20,4,35,24,11,7,62,51,6,84]

aaa.forEach((el) => console.log(el/2))

// 그냥 배열이 나열

2. 배열에서 짝수만 뽑아 배열 만들기

const aaa = [20,4,35,24,11,7,62,51,6,84]
let bbb = []

aaa.forEach(function(el) {
    if(el%2 == 0) {
       bbb.push(el) // 이 자리에 console로 찍으면 숫자가 나온다. 
       }
  	})

console.log(bbb)

//[20,4,24,62,6,84]

3. 객체 배열에서 name 키 값을 가져오기

const menu = [
      {id:1, name:'pizza', price: 12000},
      {id:2, name:'apple pie', price: 5000},
      {id:3, name:'pat thai', price: 7000},
      {id:4, name:'bulgogi', price: 8000},
      {id:5, name:'oyakodong', price: 8000},
]

menu.forEach((item) => console.log(item.name))

//
pizza
apple pie
pat thai
bulgogi
oyakodong

1. map 함수

forEach와 동작하는 방식이 거의 같으나 호출결과를 새로운 배열로 리턴해준다.

2. 예시

const brand = ['samsung', 'apple', 'asus', 'intel']
const product = ['mobile', 'watch' 'laptop', 'cpu']

let select = brand.map((brand, i ) => product[i] + brand)

console.log(select)

//mobile samsung
// watch apple
// laptop asus
// cpu intel
profile
안녕하세요!

0개의 댓글