
for in 반복문
배열과 함께 사용할 수 있는 반복문이다.
for (const 반복 변수 in 배열 또는 객체) {
문장
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const todos = ['우유 구매', '업무 메일 확인', 'JS공부'];
for(const i in todos){
console.log(`${i}번쨰 할 일: ${todos[i]}`);
}
</script>
</body>
</html>

for of 반복문
배열이 반복될 때 사용한다. 객체는 사용할 수 없고 사용하면 TypeError를 출력한다.
for (const 반복 변수 of 배열 또는 객체) {
문장
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const todos = ['우유 구매', '업무 메일 확인', 'JS공부'];
for(const todo of todos){
console.log(`오늘의 할 일: ${todo}`);
}
</script>
</body>
</html>

for 반목문과 배열
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const todos = ['우유 구매', '메일 보기', 'JS공부']
for(let i = 0; i < todos.length; i++){
console.log(`${i}번째 할 일: ${todos[i]}`);
}
</script>
</body>
</html>

for 반목문과 배열을 반대로 출력
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const todos = ['우유 구매', '메일 보기', 'JS공부']
for(let i = todos.length -1; i>=0; i--){
console.log(`${i}번째 할 일: ${todos[i]}`);
}
</script>
</body>
</html>

'개발 > JS' 카테고리의 다른 글
const and let (0) | 2022.02.27 |
---|---|
Variables (0) | 2022.02.27 |
Basic Data Type (0) | 2022.02.27 |
사용자 정의 객체 (0) | 2021.03.16 |
이벤트와 이벤트 핸들러 (0) | 2021.03.16 |