본문 바로가기
개발공부/Javascript

JavaScript : for-Each문 정리

by 촤리 2022. 8. 7.

✅ forEach() 

배열을 순회하면서 인자로 전달한 함수를 호출하는 반복문이다.

배열 뿐만 아니라 Set이나 Map에서도 사용이 가능하다.

 

1. forEach() syntax

문법은 아래와 같고 함수로 value, index, array를 전달할 수 있다.

arr.forEach(callback(value, index, array)),thisArg
  • callback : 각 요소에 대해 실행할 함수(다음 세가지 매개변수를 받는다)
  • value : 처리할 현재 요소
  • index : 처리할 현재 요소의 인덱스
  • array : forEach()를 호출한 배열
  • thisArg : callback을 실행할 때 this로 사용할 값

 

2. forEach()로 배열 순회 - 1

forEach로 배열을 순회하면서 모든 요소를 출력하는 예제이다.

arr.forEach()의 인자로 함수를 전달하면 배열의 모든 요소를 순회할 떄, 함수의 인자로 요소를 전달한다.

function myFunction(item){
console.log(item);
}

const arr = ['apple','kiwi','grape','orange']

arr.forEach(myfunction);

 

- 결과값

apple
kiwi
grape
orange

 

3. forEach()로 배열 순회 - 2 Lambda(Arrow function)으로 구현

forEach()는 화살표 함수로도 구현이 가능하다.

이렇게 구현하는 것이 코드가 좀더 간결하다.

const arr = ['apple','kiwi','grape','orange']

arr.forEach((item) =>{
console.log(item);
});

- 결과값

apple
kiwi
grape
orange

 

4. forEach()로 배열 순회 - 3 value, index를 인자로 받기

const arr = ['apple', 'kiwi', 'grape', 'orange']

arr.forEach((item, index) = > {
console.log('index: ' + index + ', item: ' + item);
});

- 결과값

index: 0, item: apple
index: 1, item: kiwi
index: 2, item: grape
index: 3, item: orange

 

5. forEach()로 배열 순회 - 4 value, index, array를 인자로 받기

const arr = ['apple', 'kiwi', 'grape', 'orange']

arr.forEach((item, index, arr)=>{
    console.log(`index: ${index} item: ${item} arr[${index}]: ${arr[index]}`);
})

- 결과값

index: 0 item: apple arr[0]: apple
index: 1 item: kiwi arr[1]: kiwi
index: 2 item: grape arr[2]: grape
index: 3 item: orange arr[3]: orange

 

6. Set 에서 forEach()로 요소 순회

Set의 모든 요소를 순회하면서 출력할 수 있다.

const set = new Set([1, 2, 3]);
set.forEach((item) => console.log(item));

- 결과값

1
2
3

 

7. Map에서 forEach()로 요소 순회

let map = new Map();
map.set('name', 'John');
map.set('age', '30');

map.forEach((value) => console.log(value));

- 결과값

John
30

 

댓글