지식사랑 2012. 8. 17. 12:38

종종 반복되는 코드의 같은 블록을 루프를 사용하여 스크립트를 작성할 수 있습니다.

대표적인 반복문으로는  for문과 while문이 있습니다.


For 문 : 특정 숫자의 차례동안 블록을 수행하는 반복문

while문 : 특정조건이 참이 되는 동안 블록을 수행하는 반복문



for Loop


for (variable=startvalue;variable<endvalue;variable=variable+increment)

{

  code to be executed

 }


예제

<!DOCTYPE html>

<html>

<body>


<p>Click the button to loop through a block of code five times.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>


<script type="text/javascript">

function myFunction()

{

var x="",i;

for (i=0; i<5; i++)

{

 x=x + "The number is " + i + "<br />";

}

document.getElementById("demo").innerHTML=x;

}

</script>


</body>

</html>




for~in Loop

이것은 오브젝트의 속성만큼 구문을 반복합니다.


for (variable in object)

{

  code to be executed

}


예제

<!DOCTYPE html>

<html>

<body>

<p>Click the button to loop through the properties of an object named "person".</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>


<script type="text/javascript">

function myFunction()

{

var x;

var txt="";

var person={fname:"John",lname:"Doe",age:25}; 


for (x in person)

{

txt=txt + person[x];

}

document.getElementById("demo").innerHTML=txt;

}

</script>

</body>

</html>



while Loop

이것은 특정조건이 참이 되는 동안 블록을 수행하는 반복문입니다.


while (variable<endvalue)

{

  code to be executed

}


예제

<!DOCTYPE html>

<html>

<body>


<p>Click the button to loop through a block of as long as <em>i</em> is less than 5.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>


<script type="text/javascript">

function myFunction()

{

var x="",i=0;

while (i<5)

{

 x=x + "The number is " + i + "<br />";

 i++;

}

document.getElementById("demo").innerHTML=x;

}

</script>


</body>

</html>



do~while Loop

이것은 while문과 유사합니다.


do

{

  code to be executed

}

while (variable<endvalue);


예제

<!DOCTYPE html>

<html>

<body>


<p>Click the button to loop through a block of as long as <em>i</em> is less than 5.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>


<script type="text/javascript">

function myFunction()

{

var x="",i=0;

  do { 

      x=x + "The number is " + i + "<br />"; i++;

  

  while (i<5);

document.getElementById("demo").innerHTML=x;

}

</script>


</body>

</html>



break 문

break 문은 강제로 빠져나갈때 사용합니다.


예제

<!DOCTYPE html>

<html>

<body>


<p>Click the button to do a loop which will skip the step where i=3.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>


<script type="text/javascript">

function myFunction()

{

var x="",i=0;

for (i=0;i<10;i++)

  {

  if (i==3)

    {

break;

      //continue;  이것은 현재의 구간에서만 break되고 다음 loop부터 실행됩니다.

    }

  x=x + "The number is " + i + "<br />";

  }

document.getElementById("demo").innerHTML=x;

}

</script>


</body>

</html>