본 수업은 폐지 예정입니다. 자바스크립트 언어 수업과 웹브라우저 자바스크립트로 수업이 리뉴얼 되었기 때문에 이것을 이용해주세요.
반복문(loop, iteration)은
- 반복적인 작업을 수행
- 조건이 프로그램을 똑똑하게 만든다면, 반복은 프로그램을 강력하게 만듬
- 종료되는 조건을 잘못 지정하면 무한반복에 빠짐 - 가장 심각한 오류 중의 하나
- for, while 문이 있음
형식 - for
1 2 3 | for( 초기화 ; 반복조건 ; 반복코드 ) { 반복시 실행되는 로직 } |
example1.html - (jsfiddle, github)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <!DOCTYPE html> < html > < head > < meta http-equiv = "Content-Type" content = "text/html;charset=utf-8" > </ head > < body > < script > for (var i = 0; i < 10 ; i++) { document.write(i); document.write('<br />'); } </ script > </ body > </ html > |
형식 - while
1 2 3 | while(반복조건) { 반복시 실행되는 로직 } |
example2.html - (jsfiddle, github)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <!DOCTYPE html> < html > < head > < meta http-equiv = "Content-Type" content = "text/html;charset=utf-8" > </ head > < body > < script > var i = 0; while (i < 5 ) { document.write(i); document.write(','); i++; } </script> </ body > </ html > |
break : 반복을 종료한다.
example3.html - (jsfiddle, github)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <!DOCTYPE html> < html > < head > < meta http-equiv = "Content-Type" content = "text/html;charset=utf-8" > </ head > < body > < script > var i = 0; while(true) { if (i == 3) { break; } document.write("The number is " + i); document.write("< br />"); i++; } </ script > </ body > </ html > |
continue : 현재 로직을 종료하지만 반복은 유지한다
example4.html - (jsfiddle, github)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <!DOCTYPE html> < html > < head > < meta http-equiv = "Content-Type" content = "text/html;charset=utf-8" > </ head > < body > < script > for ( i = 0; i <= 10; i++) { if (i == 3) { continue; } document.write("The number is " + i); document.write("< br />"); } </ script > </ body > </ html > |
반복문의 중첩
example5.html - (jsfiddle, github)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <!DOCTYPE html> < html > < head > < meta http-equiv = "Content-Type" content = "text/html;charset=utf-8" > </ head > < body > < script > for ( i = 0; i < 10 ; i++) { for ( j = 0 ; j < 10; j++) { document.write(i + '' + j + '<br />'); } } </ script > </ body > </ html > |