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);
})