JS_forEach함수

Mary·2025년 1월 24일
0

JavaScript

목록 보기
14/23
post-thumbnail

📌 forEach()란?

  • forEach()배열(Array)이나 NodeList 같은 반복 가능한 객체에서 각각의 요소를 순회하며 함수를 실행하는 메서드야.
  • for 반복문을 대신해서 더 깔끔한 코드 작성이 가능함! 🚀

✅ 기본 문법

array.forEach(function(element, index, array) {
    // 실행할 코드
});

📌 element → 현재 요소
📌 index → 현재 요소의 인덱스 (선택 사항)
📌 arrayforEach()를 호출한 배열 자체 (선택 사항)


forEach() 기본 예제

const numbers = [1, 2, 3, 4, 5];

numbers.forEach(function(num) {
    console.log(num);
});

결과:

1
2
3
4
5

배열 numbers의 모든 요소를 하나씩 꺼내서 console.log() 실행!


for 문과 비교 (forEach()가 더 깔끔!)

🔹 일반 for

const numbers = [1, 2, 3, 4, 5];

for (let i = 0; i < numbers.length; i++) {
    console.log(numbers[i]);
}

🔹 forEach()를 사용하면 코드가 더 간결해짐

numbers.forEach(num => console.log(num));

결과는 동일하지만, forEach()가 훨씬 깔끔함!


forEach()에서 index 값 사용

const fruits = ["🍎", "🍌", "🍊"];

fruits.forEach((fruit, index) => {
    console.log(`Index ${index}: ${fruit}`);
});

결과:

Index 0: 🍎
Index 1: 🍌
Index 2: 🍊

📌 현재 순회 중인 요소의 인덱스도 함께 출력 가능!


NodeList.forEach() (HTML 요소 순회)

👉 이게 실무에서 많이 사용됨!
HTML의 여러 개 요소를 선택한 후, forEach()를 사용하여 이벤트 리스너 추가 가능.

const buttons = document.querySelectorAll(".btn");

buttons.forEach(button => {
    button.addEventListener("click", () => {
        console.log(`${button.textContent} 버튼이 클릭됨!`);
    });
});

모든 .btn 클래스 버튼에 클릭 이벤트 추가!


🚀 최종 정리

forEach() 특징설명
배열 및 NodeList 요소를 순회배열의 모든 요소를 반복해서 실행
for 문보다 간결함forEach()를 사용하면 코드가 더 직관적
각 요소에 쉽게 이벤트 추가 가능HTML 요소 선택 후 forEach()addEventListener() 적용 가능

👉 즉, forEach()for 문을 대체하는 더 깔끔한 반복문이라고 보면 돼! 🚀

0개의 댓글