
while (조건식)
실행문;
두 가지 방법을 통해 반복문에서 빠져나올 수 있다.
> let i = 0;
while (true) {
if (i === 5) break;
i++;
}
console.log(i);
< 5
// i = 0 -> i = 1 / i = 1 -> i = 2 / i = 2 -> i = 3 / i = 3 -> i = 4 / i = 4 -> i = 5 / i = 5 -> break, console.log(i) -> i = 5
continue 문은 현재 또는 레이블이 지정된 루프의 현재 반복에서 명령문의 실행을 종료하고 반복문의 처음으로 돌아가여 루프문의 다음 코드를 실행한다.
> let i = 0;
while (i < 10) {
i++;
if (i % 2 === 0) { // 짝수일 때
continue; // 건너뛰기
}
console.log(i);
}
// 해당 코드는 건너뛰게되어 홀수만 출력 됨.
for (시작; 조건식; 종료식)
실행문;
Array, Map, Set에 사용되는 반복문
각 요소를 한 번씩 순회한다.
배열의 메서드이므로 문자열에는 사용할 수 없다.
for ...in반복문
객체에 주로 사용하는 반복문
객체를 순회하면서 자료들을 하나씩 꺼내고 싶을 때 사용한다.
let book = {
title: "렛츠기릿자바스크립트",
author: "제로초",
publisher: "길벗",
}
//key를 받는 변수명은 임의변경 가능
//in 객체명
for (let key in book) {
console.log(key, book[key])
}
참조
참고: javascript - foreach 문 , for in 문 , for of문
주로 배열에서 사용하는 반복문으로, iterable 한 객체에 사용할 수 있다. (문자열 포함)
배열 days를 돌면서 요소를 day 라는 이름으로 접근할 수 있다.
for 문 보다는 간단하지만 index 를 못 얻는다는 단점이 있다.
const array1 = ['a', 'b', 'c'];
for (const element of array1) {
console.log(element);
}
// Expected output: "a"
// Expected output: "b"
// Expected output: "c"
for (let i = 0; i < 10; i++) {
for (let j = 0; j < 10; j++) {
console.log(i, j);
}
}
0 0 // i=0 j=0 console.log(0,0)
0 1 // i=0 j=1 console.log(0,1)
0 2
...
0 9 // i=0 j=9 console.log(0,9) / i=0 j=10 조건문 x
1 0 // i=1 j=0 console.log(1,0)
...
9 9
for (let i = 0; i < 5; i++) {
if (i % 2 === 0) continue;
for (let j = 0; j < 5; j++) {
if (j % 2 === 0) continue;
for (let k = 0; k < 5; k++) {
if (k % 2 === 0) continue;
console.log(i, j, k);
}
}
}
// i=0 continue, i=1 j=0 continue, i=1 j=1 k=0 continue
1 1 1 // i=1 j=1 k=1 console.log, i=1 j=1 k=2 continue
1 1 3 // i=1 j=1 k=3 console.log, i=1 j=1 k=4 continue, , i=1 j=1 k=5 조건문 x
1 3 1 // i=1 j=2 continue, i=1 j=3 k=0 continue, , i=1 j=3 k=1 console.log
1 3 3 // ...
3 1 1
3 1 3
3 3 1
3 3 3
2중 for문, repeat, map을 사용하여 찍을 수 있다.
for (let i=1; i<=3+1; i++){
let arr = [];
for (let j=0; j<=i; j++){
arr.push('*');
}
console.log(arr)
}
*
**
***
//------------------------------
for (let i = 4; i > 0; i--) {
console.log('*'.repeat(i))
}
****
***
**
*
//------------------------------
for (let i = 0; i <= 7; i++) {
if(i%2!=0){
console.log(' '.repeat((7-i)/2) + '*'.repeat(i) + ' '.repeat((7-i)/2))
}
}
*
***
*****
*******
//------------------------------
console.log(Array.from({ length: 4 }, (_, i) => "*".repeat(i + 1)).join("\n"));
*
**
***
****