1. for문 사용
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
<p id="demo"></p>
<script>
const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
let text = "";
for (let i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
$("#demo").html(text);
</script>
</body>
</html>
자바스크립트의 배열을 반복문으로 출력한다.
2. for-in 문
객체의 속성을 순회할 때 사용
<script>
let obj = { a: 1, b: 2, c: 3 };
for (let prop in obj) {
console.log(prop); // 'a', 'b', 'c'가 차례로 출력됩니다.
}
</script>

3. for-of 문
배열이나 이터러블 객체를 순회할 때 사용
<script>
let array = [1, 2, 3, 4, 5];
for (let value of array) {
console.log(value); // 1부터 5까지 배열 값 출력
}
</script>

배열을 for-in 문으로 출력하면 인덱스의 값이 출력된다.
<script>
let array = [1, 2, 3, 4, 5];
for (let value in array) {
console.log(value); // 0부터 4까지 인덱스 출력
}
</script>

4. while 문
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
<h2>JavaScript While Loop</h2>
<p id="demo"></p>
<script>
let text = "";
let i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
$("#demo").html(text);
</script>
</body>
</html>

Share article