Search
Duplicate

forEach() 함수

생성일
2023/01/30 13:56
태그
JS

forEach() 함수

forEach()

배열을 순회하면서 인자로 전달한 함수를 호출하는 반복문
배열 뿐만 아니라, Set이나 Map에서도 사용 가능

forEach() Syntax

arr.forEach(func(value, index, array)) // value : 현재 순회 중인 요소 // index : 현재 순회 중인 요소의 index // array : 배열 객체
JavaScript
복사

forEach()로 배열 순회

function myFunc(item) { console.log(item); } const arr = ['apple', 'kiwi', 'grape', 'orange']; arr.forEach(myFunc); // output // // apple // kiwi // grape // orange
JavaScript
복사

forEach()로 배열 순회 : Lambda(화살표 함수)로 구현

const arr = ['apple', 'kiwi', 'grape', 'orange']; arr.forEach((item) => { console.log(item); });
JavaScript
복사

forEach()로 배열 순회 : value, index, array 인자 받기

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 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
JavaScript
복사

set에서 forEach()로 요소 순회

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

map에서 forEach()로 요소 순회

let map = new Map(); map.set('name', 'John'); map.set('age', '30'); map.forEach((value) => console.log(value)); // John // 30 let map = new Map(); map.set('name', 'John'); map.set('age', '30'); map.forEach ((value, key) => console.log("key: " + key + ", value: " + value)); // key: name, value: John // key: age, value: 30
JavaScript
복사