배열에서의 반복문 사용은 다음과 같다
// 변수 fruits 에 과일 배열에 들어갈 목록을 선언합니다.
let fruits = ['apple', 'mango', 'grape', 'orange'];
// for 반복문을 이용하여 배열의 목록을 하나씩 출력합니다.
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
하지만 객체에서의 반복문 사용은 인덱스를 사용하지 않고 변수에 저장하는 방식을 사용한다.
// 객체를 만듭니다.
let score = {
철수: 80,
영희: 77,
백호: 79,
태웅: 82
};
// names 라는 변수에 score 객체를 지정해줍니다.
for (let names in score) {
// names(속성) 과 score[names](값) 을 출력합니다.
// score[names]에서의 names는 배열과 같은 역할을 합니다.
console.log(names, score[names]);
}
댓글