๐ป Programming/Javascript
[Javascript / ์๋ฐ์คํฌ๋ฆฝํธ] ๊ฐ์ข #9 - break, continue, label ์ฌ์ฉํ๊ธฐ
์ค๋์ break๋ฌธ๊ณผ continue๋ฌธ, ๊ทธ๋ฆฌ๊ณ label์ ์ด๋ป๊ฒ ์ฌ์ฉํ๋์ง ํ๋ฒ ์์๋ณด๋๋ก ํ๊ฒ ์ต๋๋ค.
์ญ์๋ ์์ ๊ฐ ์ฐ๋ฆฌ์๊ฒ ์ต๊ณ ์ ์ค์น์ด์ฃ ? ใ
<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20)
{
if (x == 5){
break; // while๋ฃจํ์์ ๋น ์ ธ๋๊ฐ๋๋ค
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
|
x๊ฐ 5์ผ ๋ break;๋ฌธ์ด ์คํ๋๋ฉด์ ๋ฃจํ์์ ๋น ์ ธ๋์ค๊ฒ ๋ฉ๋๋ค. ๊ทธ๋์ ๊ฒฐ๊ณผ๋ ์๋์ ๊ฐ์ด ๋์ค๊ฒ ๋๊ฒ ์ฃ .
Entering the loop 2 3 4 5 Exiting the loop! |
continue ๋ฌธ์ ๊ทธ๋ผ ๋ญ๊น์? ์ ์ง break๋ฌธ์ ๋ฐ๋๊ฐ์๋ฐ ๋ง์ด์ฃ . continue๋ฌธ์ ๋ค์ ๋ฃจํ๋ก ๋์ด๊ฐ๋ผ๋ ๋ช ๋ น์ ๋๋ค. ์์ง ํ์ฌ ๋ฃจํ์์ ์คํ๋์ด์ผ ํ ๋ฌธ์ฅ๋ค์ด ๋จ์์๋๋ผ๋ ๋ง์ด์ฃ .
์๋ ์์ ๋ฅผ ํ๋ฒ ๋ณผ๊น์?
<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 10)
{
x = x + 1;
if (x == 5){
continue; // x == 5 ์ด๋ฉด x๋ฅผ ์ถ๋ ฅํ์ง์๊ณ ๋ค์ ๋ฃจํ๋ก ๋์ด๊ฐ๋๋ค.
}
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
|
๊ฒฐ๊ณผ๋ฅผ ์๋์ฒ๋ผ ๋์ค๊ฒ ์ฃ . x๊ฐ 5์ผ๋๋ continue๋ฌธ ๋๋ฌธ์ document.write( x + "<br />"); ๋ฌธ์ด ์คํ๋์ง ์์ต๋๋ค. ๋ฐ๋ผ์ 2๋ถํฐ 10๊น์ง ์ถ๋ ฅํ๋๋ฐ 5๋ง ๋นผ๊ณ ์ถ๋ ฅ์ ํ๊ฒ๋๊ฒ ์ฃ .
Entering the loop 2 3 4 6 7 8 9 10 Exiting the loop! |
Labels
JavaScript 1.2 ๋ฒ์ ๋ถํฐ label์ beak, continue๋ฌธ๊ณผ ํจ๊ป ์ฌ์ฉํ ์ ์๊ฒ ๋์ต๋๋ค.
label ์ ๊ฐ๋จํ ๋งํ๋ฉด ํน์ ์์น๋ฅผ ์ง์ ํด์ฃผ๋ ์ญํ ์ ํฉ๋๋ค.
์์ ๋ฅผ ํ๋ฒ ์ดํด๋ณด๋๋ก ํฉ์๋ค.
Example 1 : break๋ฌธ๊ณผ ํจ๊ป label์ฌ์ฉํ๊ธฐ
|
๊ฒฐ๊ณผ๋ ์๋์ฒ๋ผ ๋์ค๊ฒ ๋ฉ๋๋ค.
Entering the loop! Outerloop: 0 Innerloop: 0 Innerloop: 1 Innerloop: 2 Innerloop: 3 Outerloop: 1 Innerloop: 0 Innerloop: 1 Innerloop: 2 Innerloop: 3 Outerloop: 2 Outerloop: 3 Innerloop: 0 Innerloop: 1 Innerloop: 2 Innerloop: 3 Outerloop: 4 Exiting the loop! |
Example 2 : continue๋ฌธ๊ณผ ํจ๊ป label์ฌ์ฉํ๊ธฐ
<script type="text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 3; i++)
{
document.write("Outerloop: " + i + "<br />");
for (var j = 0; j < 5; j++)
{
if (j == 3){
continue outerloop;
}
document.write("Innerloop: " + j + "<br />");
}
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
|
๊ฒฐ๊ณผ๋ ์๋์ฒ๋ผ ๋์ต๋๋ค.
Entering the loop! Outerloop: 0 Innerloop: 0 Innerloop: 1 Innerloop: 2 Outerloop: 1 Innerloop: 0 Innerloop: 1 Innerloop: 2 Outerloop: 2 Innerloop: 0 Innerloop: 1 Innerloop: 2 Exiting the loop! |
Reference : http://www.tutorialspoint.com/javascript/javascript_loop_control.htm