본문 바로가기
프로그래밍/Javascript

javascript array 반복문

by onsil-thegreenhouse 2023. 1. 7.
반응형

javascript의 가장 많이 사용하는 array 반복문 3가지(for, for of, forEach)를 소개합니다.

 

 

 


 

1. 반복문 종류

- for문

- for of문

- forEach

  

1.1. forEach

- 매개변수로 value, index, arrary를 사용할 수 있다.


  
const arr = ['teemo', 'galio', 'yasuo'];
arr.forEach((value, index, array) => {
console.log(`value: ${value}, index: ${index}, array: ${array}`);
});
// 출력 결과
// value: teemo, index: 0, array: teemo,galio,yasuo
// value: galio, index: 1, array: teemo,galio,yasuo
// value: yasuo, index: 2, array: teemo,galio,yasuo

 

- value만 넣을 수도 있다.


  
const arr = ['teemo', 'galio', 'yasuo'];
arr.forEach((value) => {
console.log('value: ', value);
});
// 출력 결과
// value: teemo
// value: galio
// value: yasuo

 

- value, index만 넣을 수도 있다.


  
const arr = ['teemo', 'galio', 'yasuo'];
arr.forEach((value, index) => {
console.log(`value: ${value}, index: ${index}`);
});
// 출력 결과
// value: teemo, index: 0
// value: galio, index: 1
// value: yasuo, index: 2

 

  

1.2. for

- 변수 i 선언 시, const로 선언하면 값 변경이 안돼, 에러


  
const arr = ['teemo', 'galio', 'yasuo'];
for (let i=0; i < arr.length; ++i) {
console.log(`arr[${i}]: ${arr[i]}`);
};
// 출력 결과
// arr[0]: teemo
// arr[1]: galio
// arr[2]: yasuo

 

  

3.1. for of


  
const arr = ['teemo', 'galio', 'yasuo'];
for (const item of arr) {
console.log('item: ', item);
};
// 출력 결과
// item: teemo
// item: galio
// item: yasuo
반응형

댓글