for
일반적으로 지정된 횟수만큼 반복할 때 사용한다. 예를 들어 배열의 인덱스를 기반으로 반복을 수행해야하는 경우에 사용할 수 있다.
forEach
forEach문은 배열을 순회할 때 사용한다. forEach문은 배열의 각 요소에 대해 함수를 실행한다. forEach문은 첫번째 파라미터인 element를 기준으로 index를 받아오기 때문에 index로 array에 접근하는 것은 비효율적이다.
또한 break, continue 등의 제어문을 사용할 수 없다.
화살표함수 버전/일반버전
화살표함수를 쓰면 함수 내의 this값을 바깥에서 가져와 쓰기 때문에 주의.
const array = ['a', 'b', 'c'];
array.forEach(element => console.log(element));
const array = ['a', 'b', 'c'];
array.forEach(function() {
console.log(element);
});
forEach의 파라미터
const array = ['a', 'b', 'c'];
array.forEach(function(element, index, array) {
console.log(element); // a b c
console.log(index); // 0 1 2
console.log(array); // (3) ['a', 'b', 'c']
});
- 첫번째 파라미터는 array 안의 값,
- 두번째 파라미터는 array 내 index값 (0부터 1씩 증가하는 정수),
- 세번째 파라미터는 순회중인 array를 나타낸다.
for in
for in은 object 다룰 때 쉽다.
object에 쓰기
const object = { a: '사과', b: '배', c: '감' };
for (var property in object){
console.log(property); //a b c
console.log(object[property]); //사과 배 감
}
array에 쓰기
let students = ['흥민', '영희', '철수', '재석'];
for(let student in students){
console.log(student); // 0 1 2 3
console.log(students[student]); // 흥민 영희 철수 재석
};
출처 : 코딩애플 https://codingapple.com/ / MDN https://developer.mozilla.org/ko/
'🟨 JavaScript > 개념' 카테고리의 다른 글
| [코딩애플] Local Storage 사용법 (Session Storage, IndexedDB, Cookies, Cache Storage) (0) | 2023.04.13 |
|---|---|
| [코딩애플] ajax로 서버와 데이터 주고받기 (1) (0) | 2023.03.27 |
| [코딩애플,mdn] js로 html 생성하는 법 (appendChild, createElement, insertAdjacentHTML 등) (0) | 2023.01.18 |
| [코딩애플] 자료형 : Array, Object (특징과 차이점) (0) | 2023.01.18 |
| [코딩애플,mdn 등] 이벤트버블링과 이벤트캡쳐링 및 관련 유용한 함수들 (0) | 2023.01.16 |