
for(초기화; 조건식; 증감문){
//반복할 코드
}
for(let i=0; i<5; i++){
const text=i+"번 째 반복문<br>";
document.write(text);
}
-> 값
0번 째 반복문
1번 째 반복문
2번 째 반복문
3번 째 반복문
4번 째 반복문
-> i변수의 초기값은 0이고,
반복문이 돌 때마다 i변수의 값은 1씩 증가한다.
i의 값이 5보다 작을 동안 for문 안의 코드가 실행한다.
-> i가 5가 되면 반복문 중지
: 배열의 길이와 배열의 index를 참조하여, 배열의 값을 읽어오는 예제
const colors=['red', 'green', 'yellow'];
for(let i=0; i<colors.length; i++){
const text='This is ' + colors[i] + '<br>';
document.write(text);
}
-> 값
This is red
This is green
This is yellow
for(let i=0; i<5; i++){
for(let j=0; j<5; j++){
document.write('*');
}
document.write('<br>');
}
-> 값
*****
*****
*****
*****
*****
for(let i=0; i<5; i++){
for(let j=0; j<=i; j++){
document.write('*');
}
document.write('<br>');
}
-> 값
*
**
***
****
*****
for(let i=2; i<=9; i++){
document.write(i+'단');
document.write('<br>');
for(let j=1; j<=9; j++){
document.write(i+'*'+j+'='+(i*j));
document.wirte('<br>');
}
}
-> for문이 초기값은 0부터 시작하지만 편의를 위해 2와 1로 지정하였다.
-> 값
2단
2 1 = 2
2 2 = 4
2 3 = 6
2 4 = 8
2 5 = 10
2 6 = 12
2 7 = 14
2 8 = 16
2 * 9 = 18
...