본문 바로가기
JaveScript

forEach

by 원더링 2022. 6. 9.

forEach

 

 

▶ Array객체의 메서드 중 하나이며 배열에서만 사용할 수 있다.

 

 

 for문과 흡사하여 배열에서는 for문 대신 사용한다.

 

 

▶ return값이 없다.

 

 

▶ 콜백함수를 인자로 받아서 배열의 아이템, 인덱스, 배열을 처음부터 끝까지 호출한다.

 

// 배열.forEach((콜백함수(아이템, 인덱스(옵션), 전체배열(옵션)) {} )

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

arr.forEach(function(item, index, array) {
    console.log(item);  // 1, 2, 3, 4, 5 => 아이템들을 하나씩 소환
    console.log(index);  // 0, 1, 2, 3, 4 => 인덱스를 하나씩 소환
    console.log(array);  // [ 1, 2, 3, 4, 5 ] * 5 => 배열목록을 5번 소환
})



// 아이템 값만 사용하고 싶을때

// 1
arr.forEach(function(item) {
    console.log(item);
})


// 2 (화살표 함수)
arr.forEach((item) => console.log(item));



// 아이템, 인덱스만 사용하고 싶을때

// 1
arr.forEach(function(item, index) {
    console.log(item);
    console.log(index);
})


// 2 (화살표 함수)
arr.forEach((item, index) => {
    console.log(item);
    console.log(index);
})

 

 

 

 

'JaveScript' 카테고리의 다른 글

some & every  (0) 2022.06.09
find & findIndex  (0) 2022.06.09
Array(배열)  (0) 2022.06.08
Global(글로벌 객체)  (0) 2022.06.07
Wrapper(래퍼 객체)  (0) 2022.06.07