JavaScript
반복문 (for / while / do while / forEach / for in / for of )
정낭고
2023. 6. 5. 16:45
Loop (반복문)
<script>
var i = 0;
document.write(i + '<br>');
i = i+2;
document.write(i + '<br>');
i = i+2;
document.write(i + '<br>');
i = i+2;
document.write(i + '<br>');
i = i+2;
document.write(i + '<br>');
i = i+2; // i+=2;
document.write(i + '<br>');
</script>
▏for 반복문
- 초기문 -> 조건문 -> 반복할 일 -> 증감문 -> 조건문 -> 반복할 일 -> 증감문 … 순서로 실행
- 초기문만 제일 처음 고정되고 조건문, 반복할 일, 증감문 순서로 뺑글뺑글 실행
<pre>
for(초기문1;조건문2,5;증감문4){
반복할 일3,6;
}
// 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> ... 순서로 실행
// 초기문만 고정되고 조건문, 반복할 일, 증감문 순서로 뺑글뺑글 실행
</pre>
<script>
for(var i = 0;i<=10;i+=2){
document.write(i + '<br>');
}
</script>
▏while 반복문
<script>
/* 초기문;
while(조건){
반복할 일;
증감문;
} */
var i = 0;
while(i<=10){
document.write(i + '<br>');
i+=2;
}
</script>
▏do while 반복문
<script>
/* 초기문;
do{
반복할 일;
증감문;
} while(조건); */
var i = 0;
do{
document.write(i + '<br>');
i+=2;
} while(i<=10);
</script>
▏forEach 반복문 (★)
- 변수와 문자의 연결은 반드시 +가 필요함
- 각원소, 인덱스, 전체원소 순서 중요 (이름은 중요하지 않음)
<pre>
대상 - 배열
배열명.forEach(function(각원소,인덱스,전체원소){ 반복 할 일});
</pre>
<script>
var arr = ['a','b','c','d','e'];
arr.forEach(function(item,index,all){
document.write(item+'는 전체 배열에서' + all + '에서 ' + index+'번째 값이다')});
// 변수랑 문자와의 연결은 반드시 + 가 필요
// ex) i+ '는 0입니다' = i는 0입니다
// 각원소, 인덱스, 전체원소 순서가 중요 (이름은 중요하지 않음)
</script>
▏for in 반복문 (★)
- 객체에서만 사용 가능 (배열에서는 사용 X)
<pre>
객체 = 변수(property) + 함수(method)
객체의 값들 반복
for(각 property 변수명 in 객체명){
반복할 일;
}
</pre>
<script>
var student1 = {
kor:100, eng:80, math:90
}
console.log(student1.eng);
for(item in student1){
document.write(item + ':'+student1[item] + '<br>')
}
</script>
▏for of 반복문 (★)
- 대상이 배열일 때만 사용 가능
<pre>
for(각원소 변수 of 배열명){
반복할 일;
}
</pre>
<script>
for(item of arr){
document.write(item+'입니다<br>');
}
</script>
ex) for 반복문을 이용한 구구단 출력
<body>
<h1>2단 출력</h1>
<script>
for(var i=1; i<=9; i++){
document.write('2 x ' + i + '='+ i*2 + '<br>');
}
</script>
<hr>
<h2>3단 출력</h2>
<script>
for(var i=1; i<=9; i++){
document.write('3 x ' + i + '='+ i*3 + '<br>');
}
</script>
<hr>
<h2>구구단 출력</h2>
<script>
for(var i=2; i<=9; i++){
document.write('--------- '+i+'단 --------- <br>');
for(var x=1; x<=9; x++){
document.write(i + ' x ' + x + ' = '+ i*x + '<br>');
}
}
</script>
</body>