javaScript/JS Examples

forEach 반복문으로 배열값 전체 호출하기

mooyou 2022. 4. 24. 14:20
728x90
300x250
SMALL

forEach는 반복문 중에서 오직 배열 Array 객체에서만 사용 가능한 메서드이다. (ES6부터 Map, Set 지원)

map과 비슷해 보이지만 forEach는 return값이 없다.

forEach 구문의 인자로 콜백함수를 등록해서 배열 첫 번째부터 마지막 번까지 반복해서 item을 호출하게 된다.

 

예제를 보도록 하자

let text = "";
const number = [1,2,3,4,5];
number.forEach(numArray);

function numArray(item, index) {
    console.log(index + '.' + item);
}

결과

numArray의 인자로 현재 item과 index값을 넘겨받아 출력한다.

 

만약 이 값을 차례로 html 태그 안에 나타내려면?

innerHTML 메소드를 사용해서 다음과 같이 코드를 작성해 주면 된다.

<p id="test"></p>

<script>
    let text = "";
    const number = [1,2,3,4,5];
    number.forEach(numArray);
    document.getElementById('test').innerHTML = text;

    function numArray(item, index) {
        text += index + '.' + item + '<br>';
    }
</script>

 

인자로 함수를 직접 넣어 줄 수도 있다.

let number = [1,2,3,4,5];

number.forEach(num => {
    console.log(num);
})

number배열에 forEach 메서드를 사용하는데 인자 값으로 arrow함수를 사용

 

결과

728x90
반응형
LIST