Javascript - 배열 내장함수 forEach

YuJin Lee·2020년 10월 6일
0

Javascript

목록 보기
6/22
  • 배열 내장함수
    배열을 이용할 때 알아두면 유용한 함수들

const superheros = [
  '아이언맨',
  '캡틴 아메리카',
  '토르',
  '닥터 스트레인지'
];

for (let i = 0; i < superheros.length; i++) {
  console.log(superheros[i]);
  //superheros 배열 안의 값이 하나씩 출력
}

forEach는 주어진 함수를 배열 요소에 대해 각각 실행한다.
forEach를 사용하여 위 문장을 다음과 같이 나타낼 수 있다.

const superheros = [
  '아이언맨',
  '캡틴 아메리카',
  '토르',
  '닥터 스트레인지'
];

function print(hero) {
  console.log(hero);
}

superheros.forEach(print);

또는 다음과 같이 나타낼 수 있다.

const superheroes = [
  '아이언맨',
  '캡틴 아메리카',
  '토르',
  '닥터 스트레인지'
];

superheroes.forEach(function(hero) {
  console.log(hero);
})
profile
배운 것을 기록하는 곳 💻🙂

0개의 댓글