티스토리 뷰

728x90
반응형

자바스크립트에서 반복문을 수행하는 방법으로 for문에 대해 공부해봤었다. 

이번에는 반복문을 수행하는 또 다른 방법인 forEach문에 대해 공부해보도록 하겠다.

 

forEach문은 함수를 인자로 전달한다 . 다음 예제의 주석을 읽어보자.

nums.forEach(function(item, index){});

 

예제1 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Step03_loop7.html</title>
</head>
<body>
<script>
    let nums = [10,20,30,40,50];

    //forEach함수는 함수를 인자로 전달해줘야한다.
    //따라서, forEach를 이용하여 반복문을 수행할 수 있다. 
    //전달하는 함수 내 인자는 하나일떄 item만, 두개일 때 item,과 index이다.
    nums.forEach(function(item, index){
        console.log("호출됨!");
        console.log(index+" 인덱스에 저장된 item: "+item);
    });

</script>    
</body>
</html>

 

forEach의 함수 내 인자로는 item과 index를 활용한다. 

 

 

결과

 

 

 

예제2 - forEach 함수를 이용하여 버튼 클릭 시 p 요소의 innerText값 변경하기 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Step03_example.html</title>
</head>
<body>
    <h1>배열의 forEach()함수를 활용한 반복 작업</h1>
    <p>p1</p>
    <p>p2</p>
    <p>p3</p>
    <p>p4</p>
    <p>p5</p>
    <button id = "changeBtn">바꾸기</button>
    <script>
        /*
        forEach()함수를 이용하여 바꾸기 버튼을 누르면 모든 p요소의 innerText를 "김구라"로 바꿔보세요.
        */
        document.querySelector("#changeBtn").addEventListener("click",function(){
            document.querySelectorAll("p").forEach(function(item,index){
                //함수의 첫번째 인자로 전달된 item 안에는 p요소의 참조값이 들어있다.
                item.innerText = "김구라";
            })
        });
        
    </script>
</body>
</html>

 

반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함