for loops · for 루프
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 이 페이지는 최신 브라우저(SharedArrayBuffer 지원)가 필요합니다. Chrome, Edge, Firefox 또는 Safari를 최신 버전으로 업데이트해 주세요.
English
Repeating with a for loop
- A loop runs the same block many times, so you don't repeat yourself.
for (let i = 1; i <= 5; i++) { ... }has three parts: starti = 1, testi <= 5, stepi++.
한국어
for 루프를 반복하기
- 루프는 동일한 블록을 여러 번 실행하여 코드를 중복하지 않게 합니다.
for (let i = 1; i <= 5; i++) { ... }은 세 가지部分组成으로 구성됩니다: 시작i = 1, 조건 테스트i <= 5, 증가/감소 단계i++.
for (let i = 1; i <= 3; i++) {
console.log(i); // → 1, then 2, then 3
}
English
Build a running total
- Keep a variable outside the loop and add to it on every pass.
한국어
누적 합계 만들기
- 루프 바깥에 변수를 유지하고 매번 반복할 때마다 그 값에 더합니다.
let total = 0;
for (let i = 1; i <= 10; i++) {
total = total + i;
}
console.log(total); // → 55
Explore · 탐색하기
Trace the running total · 총합 추적하기
A loop repeats its body. Step through the passes and watch total grow. · 루프는 본문을 반복합니다. 반복 과정을 단계별로 따라가며 total이 어떻게 증가하는지 확인합니다.
English
Watch out
i <= 5stops after 5;i < 5stops before 5. Picking the wrong one is the classic "off-by-one" bug.- Start the total at
0before the loop, not inside it.
한국어
주의사항
i <= 5은 5 이후에 멈춥니다;i < 5은 5 전에 멈춥다. 잘못 선택하면 고전적인 "off-by-one" 버그(한 단계 차이 오류)가 발생합니다.- 루프 내부가 아닌, 루프 시작 전에 합계를
0으로 초기화하십시오.
English
Common mistakes
for (let i = 0; i < n; i++)runsntimes.- Declare the counter with
let, not without.
한국어
흔한 실수
for (let i = 0; i < n; i++)은n회 실행됩니다.let을 사용하여 카운터를 선언하십시오, 그렇지 않으면 선언되지 않습니다.
English
Now you try
- Use a
forloop. - Press Check answer to test it.
한국어
이제 직접 해보기
for루프를 사용하십시오.- 답안 확인을 눌러 테스트해 보십시오.
Use a for loop to log the numbers 1 to 5, one per line. · for 루프를 사용하여 숫자 1부터 5까지를 각각 한 줄씩 출력합니다.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Use a for loop to add up 1 to 10, then log the total (it is 55). · for 루프를 사용하여 1부터 10까지의 합을 구한 후, 총합을 출력합니다(그 결과는 55입니다).
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Use a for loop to log the even numbers 2, 4, 6, one per line (step by 2 with i += 2). · for 루프를 사용하여 홀수인 숫자 2, 4, 6을 각각 한 줄씩 출력합니다(i += 2을 사용하여 2씩 증가시키십시오).
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.