for 루프

for 문에서는 카운터 변수, 테스트 조건 및 카운터를 업데이트하는 동작을 지정합니다. 매번 루프가 반복되기 전에 조건이 테스트됩니다. 테스트가 성공적일 경우 루프 내부의 코드가 실행됩니다. 테스트가 실패할 경우 루프 내부의 코드가 실행되지 않으며 루프 바로 다음 코드 줄부터 프로그램을 계속 실행합니다. 루프가 실행된 후 카운터 변수는 다음 반복이 시작되기 전에 업데이트됩니다.

루프 사용

루핑 조건이 한 번도 만족되지 않으면 루프는 실행되지 않으며 테스트 조건이 항상 만족되면 무한 루프가 발생합니다. 루프가 전혀 실행되지 않는 경우는 필요할 때도 있지만 무한 루프가 발생하는 경우는 바람직하지 않으므로 루프 조건을 만들 때 주의하십시오. 다음 예제에서는 for 루프를 사용하여 이전 요소의 합으로 배열의 요소를 초기화합니다.

var sum = new Array(10); // Creates an array with 10 elements
sum[0] = 0;              // Define the first element of the array.
var iCount;

// Counts from 0 through one less than the array length.
for(iCount = 0; iCount < sum.length; iCount++) { 
   // Skip the assignment if iCount is 0, which avoids
   // the error of reading the -1 element of the array.
   if(iCount!=0)
      // Add the iCount to the previous array element,
      // and assign to the current array element.
      sum[iCount] = sum[iCount-1] + iCount;
   // Print the current array element.
   print(iCount + ": " + sum[iCount]); 
}

이 프로그램은 다음과 같이 출력됩니다.

0: 0
1: 1
2: 3
3: 6
4: 10
5: 15
6: 21
7: 28
8: 36
9: 45

다음 예제에서는 루프가 두 개입니다. 첫 번째 루프의 코드 블록은 한 번도 실행되는 일이 없으며 두 번째 루프는 무한 루프입니다.

var iCount;
var sum = 0;
for(iCount = 0; iCount > 10; iCount++) { 
   // The code in this block is never executed, since iCount is
   // initially less than 10, but the condition checks if iCount
   // is greater than 10.
   sum += iCount;
}
// This is an infinite loop, since iCount is always greater than 0.
for(iCount = 0; iCount >= 0; iCount++) { 
   sum += iCount;
}

참고 항목

참조

for 문

기타 리소스

JScript의 루프

JScript 조건부 구조

JScript 참조