.forEach() , ARROW function

김세주·2021년 1월 8일
0

JavaScript

목록 보기
1/12

forEach()

MDN참조
주어진 함수를 배열 요소 각각에 대해 실행함.


array1.forEach(element => console.log(element));

// expected output: "a"
// expected output: "b"
// expected output: "c"

for 반복문을 forEach()로 바꿀 수 있다

const items = [ 'item1', 'item2', 'item3' ];
const copy = [];
// 반복문
for (let i =0; i <items.length; i++){
    copy.push(items[i]);
}
// forEach 구문 사용
items.forEach(function(item){
  copy.push(item);
});

이렇게 반복문 손쉽게 고칠 수 있음.

function logArrayElements(element, index, array) {
  console.log('a[' + index + '] = ' + element);
}

// 인덱스 2는 배열의 그 위치에 항목이 없기에
// 건너뜀을 주의하세요.
[2, 5, , 9].forEach(logArrayElements);
// 기록:
// a[0] = 2
// a[1] = 5
// a[3] = 9

이런식으로 함수가 들어가서 조건에 맞게 출력도 가능함.

function flatten(arr) {
  const result = []

  arr.forEach((i) => {
    if (Array.isArray(i)) {
      result.push(...flatten(i))
    } else {
      result.push(i)
    }
  })

  return result
}

// Usage
const nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]]

flatten(nested) // [1, 2, 3, 4, 5, 6, 7, 8, 9]

배열 평탄화 가능

forEach 는 return 이 없다 따라서 아래처럼 함수 밖에 변수를 사용해 결과를 나타내야함

const arr = [0,1,2,3,4,5,6,7,8,9,10];
const oddArray = [];

arr.forEach(function(element){
    if(element%2==1) {
        oddArray.push(element);
    }
});

console.log(oddArray); // [ 1, 3, 5, 7, 9 ]

그럼에도 불구하고

for문은 continue(지나침) 나 break(멈춤) 로 제어할 수 있다.
그러나 forEach는 throw(예외)를 발생시키지 않으면 중간에 반복을
멈출 수 없다.

Arrow function

const arr = [0,1,2,3,4,5,6,7,8,9,10];

arr.forEach(function(element){
    console.log(element); // 0 1 2 3 4 5 6 7 8 9 10
});
// 혹은 arrow 함수 가능
arr.forEach(element => console.log(element);
profile
시간은 내 편이다.

0개의 댓글