javascript강좌 (11)

이번에는 void 키워드에 대해서 한번 알아보도록 할까요?  

자바스크립트에서 사용되는 void는 자바의 void와 별반 다를게 없어보입니다.

우선 제가 조사한 바에 의하면 void의 역할을 아래와 같습니다.

void keyword evaluates the expression and always returns undefined.

한마디로 "표현식을 평가하고 항상 undefined를 반환한다"네요. 이게 무슨 말일까요? 아시는 분은 댓글좀 남겨주세요 ㅎㅎ   

사실 포스팅은 하는데 이게 도대체 언제 어떻게 쓰이는지에 대해서는 저도 잘 모르겠습니다. 어쨌든 이런 것도 있구나 하시면서 보시면 되겠습니다. 

일단 예제를 한번 보는게 낫겠죠?  

아래에 기본적인 예제가 나와있네요.

 

<head>
<script type="text/javascript">
<!--
void func()
javascript:void func()

or:

void(func())
javascript:void(func())
//-->
</script>
</head>

예제 1:

void 키워드가 가장 많이 사용되는 곳은 클라이언트 사이드의 javascript: URL​ 이라고 하네요. 이 예제에서는 alert함수를 사용했는데요

한번 실행시켜 보세요. void ( )를 없애고 그냥 alert('Warning!!!')만 써도 결과는 똑같이 나옵니다. 차이가 뭔지 저도 아직 잘 모르겠네요. 

<head>
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<a href="javascript:void(alert('Warning!!!'))">Click me!</a>
</body>

 

 

 

예제 2:

이번 예제에서는 void( )안에 "0" 만 써넣었네요. 사실 저도 이게 정확히 뭘 의미하는지 잘은 모르겠지만 제가 참조한 사이트에 의하면 다음처럼 얘기하고 있습니다. Here the expression "0" is evaluated but it is not loaded back into the current document. 0 이라는 값이 평가가 되기는 하는데 현재문서로 load되지는 않는다고 말이죠. 자, 결과가 예제 1과 뭐가 다른가요? 링크를 눌러도 아무런 변화가 안보이죠? 

<head>
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<a href="javascript:void(0))">Click me!</a>
</body>

 

 

예제 3:

이번 예제에서는 void 키워드를 사용함으로써 고의적으로 undefined 값을 a에 할당하고 있습니다. 뭐 실제로 이렇게 쓸만한 일은 없을 것 같지만 이런 예제도 있구나 하시면 될 것 같네요. 

<head>
<script type="text/javascript">
<!--
function getValue(){
   var a,b,c;

   a = void ( b = 5, c = 7 );
   document.write('a = ' + a + ' b = ' + b +' c = ' + c );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="getValue();" />
</body>

 

 

 

예제 4:

마지막 예제입니다. 이번 예제에서는 void( )안에서특정 변수에 값을 할당하고 할당된 값을 경고창을 이용해서 뿌려주고있습니다.

사실 void키워드가 없어도 결과는 동일하게 나옵니다만....도대체 왜 void키워드를 쓰는지는 모르겠네요 ㅎㅎ;;;; 

<head>
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<a href="javascript: void(myNum=10);alert('myNum = '+myNum)">
Set myNum Please</a>
</body>

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_void_keyword.htm

 

 

 

자바스크립트는 세 종류의 다이얼로그 박스를 제공합니다. 어떤 것들이 있는지 한번 볼까요??  

경고

사용자에게 경고메시지를 보여줄 때 사용하는 박스죠. 필수값을 입력하지 않고 진행하려는 사용자에게 경고를 할 때 주로 사용합니다. 

 

<head>
<script type="text/javascript">
<!--
   alert("Warning Message");
//-->
</script>
</head>

경고창은 OK버튼 하나만 가지고 있습니다. 뭔가를 알려주고 알겠다는 말을 해주고 사용자가 그 말을 확인했다는 확인버튼만 있는거죠. 


확인

확인창은 사용자에게 정말 실행하겠습니까? 와 같은 질문을 하고 확인을 하기 위해서 사용됩니다.그래서 버튼이 두개가 있죠. 확인버튼과 취소버튼이요.

사용자가 확인버튼을 누르면 confirm() 메소드는 참을 반환하고 취소버튼을 누르면 거짓을 반환합니다.그리고 거기에 따라서 어떠한 로직을 태울지는 개발자가 결정하면 되는거죠.

 

<head>
<script type="text/javascript">
<!--
   var retVal = confirm("Do you want to continue ?");
   if( retVal == true ){
      alert("User wants to continue!");
   return true;
   }else{
      alert("User does not want to continue!");
   return false;
   }
//-->
</script>
</head>

 


프롬프트

프롬프트 창은 사용자로부터 어떤 입력을 받을 수 있는 창입니다. prompt() 메소드를 사용하며 두개의 파라미터를 받습니다. 프롬프트창의 라벨과 창에 표시될 텍스트. 역시 버튼은 확인과 취소 두개의 버튼이 있습니다. 확인버튼을 누르면 prompt() 메소드는 입력된 값을 반환하고 취소버튼을 누르면 null을 반환합니다.


<head>
<script type="text/javascript">
<!--
   var retVal = prompt("Enter your name : ", "your name here");
   alert("You have entered : " +  retVal );
//-->
</script>
</head>

 

 직접 테스트 해보세요. 연습은 10번씩 해야 손에 익고 눈에 익고 실력으로 남습니다. 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_dialog_boxes.htm

 


기본적인 페이지 리디렉션

간단한 페이지 리디렉션은 아래처럼 하시면 되요~

<head>
<script type="text/javascript">
<!--
   window.location="http://www.newlocation.com";
//-->
</script>
</head>

 

 


리디렉션 메시지를 보여주고 특정 시간 후에 리디렉션하기

<head>
<script type="text/javascript">
<!--
function Redirect()
{
    window.location="http://www.newlocation.com";
}

document.write("You will be redirected to main page in 10 sec.");
setTimeout('Redirect()', 10000);
//-->
</script>
</head>

여기서 사용된 setTimeout() 메소드는 JavaScript에서 기본으로 제공하는 메소드로 특정 시간 후에 다른 함수를 호출할 수 있게끔 해줍니다.

 


브라우저 종류에 따른 리디렉션

<head>
<script type="text/javascript">
<!--
var browsername=navigator.appName; 
if( browsername == "Netscape" )
{ 
   window.location="http://www.location.com/ns.htm";
}
else if ( browsername =="Microsoft Internet Explorer")
{
   window.location="http://www.location.com/ie.htm";
}
else
{
  window.location="http://www.location.com/other.htm";
}
//-->
</script>
</head>

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_page_redirect.htm

 

 

 


이번에는 쿠키를 다루는 방법에 대해서 알아보도록 하겠습니다. ^___^

Cookies 만들기

문법부터 보도록 하겠습니다.
document.cookie = "key1=value1;key2=value2;expires=date";

여기서 expires 속성은 옵션입니다. 쿠키의 생명주기를 지정해주는 속성이죠. 지정된 시일이 지나면 쿠키는 더이상 유효하지 않게됩니다.

Note: 쿠키 값은 세미콜론이나 쉼표 또는 스페이스를 포함할 수 없습니다. 그래서 저장하기 전에 escape() 함수를 이용해서 인코딩한 값을 이용하기도 하죠. escape()함수로 인코딩해서 저장을 했을 때는 unescape() 함수를 이용해서 decode해야 쿠키값을 제대로 읽어올 수 있습니다.

 

 

아래 예제는 input쿠키에 customer의 이름을 저장하는 것을 보여주고있습니다.

<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
   if( document.myform.customer.value == "" ){
      alert("Enter some value!");
      return;
   }

   cookievalue= escape(document.myform.customer.value) + ";";
   document.cookie="name=" + cookievalue;
   alert("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
</form>
</body>
</html>

Cookies 읽기

​자바스크립트에서 쿠키는 document.cookie 객체라는 것은 위에서 알게되셨을겁니다. 쿠키에는 key, value페어가 여러개가 들어가있을 수 있습니다. 그리고 key와 value는 각각 세미콜론으로 구분이 되어집니다. 따라서 쿠키를 읽을때는 split() 함수를 사용하게 됩니다.

 

 

예제를 한번 보시죠.

<html>
<head>
<script type="text/javascript">
<!--
function ReadCookie()
{
   var allcookies = document.cookie;
   alert("All Cookies : " + allcookies );

   // Get all the cookies pairs in an array
   cookiearray  = allcookies.split(';');

   // Now take key value pair out of this array
   for(var i=0; i<cookiearray.length; i++){
      name = cookiearray[i].split('=')[0];
      value = cookiearray[i].split('=')[1];
      alert("Key is : " + name + " and Value is : " + value);
   }
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form>
</body>
</html>

 

 

위 소스는 여러분 컴퓨터에 저장된 쿠키를 읽어들여서 키, 값 페어를 화면에 출력하게됩니다. 

직접 한번 실행해 보세요~~ ^__^ 

Cookies 만료일자 설정하기

예제로 배워봅시다~~ 아래 예제는 쿠키의 만료일자를 1달뒤로 설정하는 코드입니다.

 

<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
   var now = new Date();
   now.setMonth( now.getMonth() + 1 ); 
   cookievalue = escape(document.myform.customer.value) + ";"
   document.cookie="name=" + cookievalue;
   document.cookie = "expires=" + now.toUTCString() + ";"
   alert("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>

Cookie 삭제하기

삭제를 하는 것은 실제로 삭제를 하는것이 아니라 단지 만료일자를 과거일자로 세팅하는 것입니다.

아래 예제를 보실까요?


<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
   var now = new Date();
   now.setMonth( now.getMonth() - 1 ); 
   cookievalue = escape(document.myform.customer.value) + ";"
   document.cookie="name=" + cookievalue;
   document.cookie = "expires=" + now.toUTCString() + ";"
   alert("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>

 

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_cookies.htm 

 

 

 


Event 란?

이벤트가 뭘까요? 이벤트는 어떤 동작이라고 생각하시면 됩니다. 웹브라우저를 사용하는 사용자가 또는 웹브라우저가 어떤 동작을 하는 것을 이벤트라고 합니다. 생일파티나 축하이벤트 같은 그런 것과 혼동하시면 안됩니다 ㅋㅋㅋ

 

가장 흔하게 쓰이는 이벤트는 클릭입니다. 사용자가 어떤 버튼을 클릭하는 것. 이것도 하나의 이벤트이죠.

그럼 온클릭 이벤트에 대해서 한번 살펴볼까요? 

onclick 예제

<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
   alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>

 

위 소스는 화면에 버튼을 하나 생성합니다. 그리고 그 버튼을 누르면 sayHello()함수를 호출하게 됩니다.

 

onsubmit 예제

onclick 이벤트 다음으로 많이 쓰이는게 아마 onsubmit이벤트일겁니다. 이 이벤트는 폼 태그에서 사용자가 submit하게 되면 발생하는 이벤트죠.

  

<html>
<head>
<script type="text/javascript">
<!--
function validation() {
   // 유효성 검사를 여기다가 하시면됩니다.
   .........
   return true  // or false
}
//-->
</script>
</head>
<body>
<form method="POST" action="t.cgi" onsubmit="return validate()">
.......
<input type="submit" value="Submit" />
</form>
</body>
</html>

 

위 소스를 분석해보면...음...submit버튼이 있고 submit버튼이 눌릴때 return validate()를 하는데 이는 validate()에서 받은 결과를 반환하겠다는 의미입니다.


onmouseover 와 onmouseout:

이 이벤트들은 마우스가 화면의 특정 지역 안에 있는지 또는 특정 지역 안에 있다가 밖으로 나갔는지를 체크하여 특정 기능을 수행할 수 있도록 도와줍니다.

예제를 한번 살펴보죠.

 

<html>
<head>
<script type="text/javascript">
<!--
function over() {
   alert("Mouse Over");
}
function out() {
   alert("Mouse Out");
}
//-->
</script>
</head>
<body>
<div onmouseover="over()" onmouseout="out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>

 

마우스가 <div>태그 내의 내용물 ( 화면에 보여지는 ) 위에 있으면 over()함수를 호출하고 밖으로 나가면 out()함수를 호출합니다. 

 

HTML 4 표준 이벤트

아래는 표준 이벤트들의 목록입니다. 위에서 해본것을 바탕으로 이런저런 기능드을 한번 테스트 해보세요~~ ^___^

 

EventValueDescription
onchangescriptScript runs when the element changes
onsubmitscriptScript runs when the form is submitted
onresetscriptScript runs when the form is reset
onselectscriptScript runs when the element is selected
onblurscriptScript runs when the element loses focus
onfocusscriptScript runs when the element gets focus
onkeydownscriptScript runs when key is pressed
onkeypressscriptScript runs when key is pressed and released
onkeyupscriptScript runs when key is released
onclickscriptScript runs when a mouse click
ondblclickscriptScript runs when a mouse double-click
onmousedownscriptScript runs when mouse button is pressed
onmousemovescriptScript runs when mouse pointer moves
onmouseoutscriptScript runs when mouse pointer moves out of an element
onmouseoverscriptScript runs when mouse pointer moves over an element
onmouseupscriptScript runs when mouse button is released

 

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_events.htm 

 

 


이번에는 자바스크립트의 함수에 대해서 알아보도록 하겠습니다.  

함수가 뭐냐? 모르시는 분이 계시려나요? 자바나 C의 메소드, 함수랑 똑같은 겁니다.

함수는 function 키워드를 이용해서 정의하는데 function의 영어 의미를 찾아보면 다음과 같습니다.

1.명사 (사람사물의) 기능
2.명사 행사, 의식
3.동사 (제대로) 기능하다[작용하다] (=operate)

따라서 함수는 특정 기능을 하는 놈이구나~ 라고  이해하시면 됩니다.

내가 원하는 어떤 기능을 하도록 만드는 것이죠.

 

자, 그럼 문법을 한번 살펴보겠습니다.

<script type="text/javascript">

function 함수명( 파라미터 리스트 )
{
  // statements
}

</script>

 

 

위 문법은 함수를 선언하는 것입니다. 아래처럼 사용할 수 있죠. 

<script type="text/javascript">

function sayHello()
{
   alert("Hello there");
}

</script>

 

 

 

자, 그럼 이렇게 선언해놓은 함수를 어떻게 호출을 할까요?

 

네~ 그렇죠~ 제가 늘 말하는 "아래처럼" 호출하면 되는겁니다~

 

<script type="text/javascript">

sayHello();

</script>

 

 

파라미터

이번에는 파라미터 사용법에 대해서 알아보도록 하겠습니다.

 

자바스크립트의 특징 중 하나가  undefined type이었다는 것을 기억하시나요? 변수를 지정할때 타입을 지정하지를 않죠?  

함수내에 파라미터를 넣을때도 타입을 지정하지 않습니다. 아래처럼 말이죠. 

<script type="text/javascript">

function sayHello(name, age)
{
   alert( name + " is " + age + " years old.");
}

</script>

 

위 소스를 보시면 sayHello()가 파라미터 두개를 받고있네요. name과 age.  

이 함수를 호출할 때에는 파라미터를 두개 넣어주면 되는 겁니다. 

<script type="text/javascript">

sayHello('Zara', 7 );

</script>

 

sayHello 함수에 'Zara' 랑 7을 파라미터로 넘겼네요. Zara의 홑따옴표는 스트링을 의미합니다. Zara라는 스트링을 파라미터로 넘긴다는 말이죠. 

return

자바스크립트의 함수도 결과값을 반환할 수 있습니다. 

 

예제를 한번 볼까요? 

 

<script type="text/javascript">

function concatenate(first, last)
{
   var full;

   full = first + last;
   return  full;
}

</script>

위 소스는 두개의 파라미터를 받아서 두개를 합친 결과를 반환합니다.

 

이제 함수를 호출해서 함수에서 얻은 결과값을 경고창에 띄워보겠습니다. 

<script type="text/javascript">

   var result;
   result = concatenate('Zara', 'Ali');
   alert(result );

</script>

 

 

함수에 대해서 좀 더 자세한 내용을 알고싶으면 아래 링크를 참조하세요 ^____^

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_functions.htm 

 

 

 

오늘은 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사용하기

<script type="text/javascript"> <!-- document.write("Entering the loop!<br /> "); outerloop: // 1번 라벨입니다. for (var i = 0; i < 5; i++) // 1번 루프 { document.write("Outerloop: " + i + "<br />"); innerloop: // 2번 라벨입니다. for (var j = 0; j < 5; j++) // 2번 루프 { if (j > 3 ) break ; // 이 문장을 포함하는 가장 가까운 루프를 빠져나옵니다. (여기서는 2번 루프겠죠) if (i == 2) break innerloop; // 이 문장은 innerloop를 빠져나와는 말입니다. ( 2번 루프에서 나오는거죠 ) if (i == 4) break outerloop; // 이 문장은 outerloop를 빠져나옵니다. ( 1번 루프에서 빠져나가는 것이죠 ) document.write("Innerloop: " + j + " <br />"); } } document.write("Exiting the loop!<br /> "); //--> </script>

 

결과는 아래처럼 나오게 됩니다. 

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 

 

 


자~ 오늘은 for 루프에 대해서 알아보도록 하겠습니다.

 

for 루프와 while루프는 100% 바꿔치기가 가능한 녀석들입니다. 어떤 상황에서 어떤 반복문을 사용하느냐는 개발자인 여러분들에게 달려있습니다!!  

우선 문법부터 확인해야겠죠? 어떻게 생긴놈인지 알아야 뭘 써먹더라도 써먹죠 ㅋㅋ 

 

for ( 초기화 ; 조건문 ; 반복실행문 ){
     조건문이 참인 동안 실행되어야 할 문장
}

역시 우리는 예제가 있어야 뭘 알것 같아요 그죠잉?
<script type="text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++){
  document.write("Current Count : " + count );
  document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>

 

자 위 코드를 보면 어떤 결과가 나올거라고 예상이 되시나요??  

아래 해답을 보시죠.  

 

Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped! 

 

어때요? 쉽죠? 어려우시다구요? 그럼 설명을 좀 해드릴게요.

 

for ( count = 0 ; count < 10 ; count++ ) : for루프를 시작하는 부분입니다. 변수 count를 0으로 초기화 합니다. count변수의 값이 10보다 작을 동안 실행하라는 조건을 줬습니다. 그리고나서 매 루프가 끝나면 count를 1씩 증가시키도록 합니다.

여기서 세미콜론 ( ; ) 잊어먹지 않도록 조심하세요.

문법이 어렵다면 연습만이 당신을 살릴 수 있으니 연습하세요. ㅋㅋ

 

 

자, 또 다른 for 루프가 있습니다. 객체를 이용하는 것인데요~ 형식을 한번 볼까요?

 

 

for (변수명 in 객체){
  실행할 문장
}

 

 

 

아래 예제는 웹브라우저의 Navigator객체에 있는 속성을 출력하는 기능을 for루프로 구현해놓은 것입니다. 

<script type="text/javascript">
<!--
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator)
{
  document.write(aProperty);
  document.write("<br />");
}
document.write("Exiting from the loop!");
//-->
</script>

 

결과는 아래처럼 나오겠죠? 아닌가요? 맞나? 확인해보세요~~ ^___^ 

Navigator Object Properties
appCodeName
appName
appMinorVersion
cpuClass
platform
plugins
opsProfile
userProfile
systemLanguage
userLanguage
appVersion
userAgent
onLine
cookieEnabled
mimeTypes
Exiting from the loop! 

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_for_loop.htm 

 

 


이번 포스팅에서는 자바스크립트의 while 루프문에 대해서 알아보도록 하겠습니다.

 

우선 문법부터 확인해볼까요??

 

 

while (조건문){
   조건문이 참인동안 실행해야할 문장
}

 

이제 예제를 한번 볼까요??
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br />");
while (count < 10){
  document.write("Current Count : " + count + "<br />");
  count++;
}
document.write("Loop stopped!");
//-->
</script>

 

결과가 어떻게 나올것 같나요??

아래처럼 나와야겠죠??

 

Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped! 

 

 

 

 

자 while문과 비슷한 do-while문을 아시나요? do-while문은 일단 먼저 한번 실행시킨 다음에 while문을 타는겁니다.

역시 말보다는 실습이죠? 

 

문법부터 확인해볼까요??
do{
  최소 한번은 실행되어야 하는 문장
} while (조건문);

그럼 이제 예제를 한번 봅시다.
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br />");
do{
  document.write("Current Count : " + count + "<br />");
  count++;
}while (count < 0);
document.write("Loop stopped!");
//-->
</script>

 

결과가 예상이 되나요?

아래처럼 결과를 예상하셨다면 당은은 자바스크립트의 중수가 되신겁니다~ 축하드려용~~ㅋㅋ 

Starting Loop
Current Count : 0
Loop stopped! 

 

간단하죠??

별거 없습니다 ㅎㅎ

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_while_loop.htm

 

 


JavaScript 1.2부터 switch문을 사용할 수 있습니다. switch문이 뭐냐? 문법부터 일단 보시죠. 

 

switch 문은 크게 switch절과 case절 그리고 default절이 있습니다. switch절에는 변수가 들어가는데 if문에서처럼 참, 거짓을 반환하는조건이 들어가는 것이 아닙니다. 이 변수는 어떤 값을 가지고 있겠죠? 그 값들을 case 절에 써주는 겁니다. case절은 여러개가 올 수 있는데 만약 모든 case절에서 매치되는 값을 못찾으면 default절의 문장을 실행하고 switch문은 종료됩니다.

switch (변수)
{
  case 값1: statement(s)
                    break;
  case 값2: statement(s)
                    break;
   ...
  case 값n: statement(s)
                    break;
  default: statement(s)
}

break 문은 특정 case가 끝났다고 알려주는 문장입니다. 만약 이 break문이 없으면 밑에있는 case안에 있는 문장들도 실행을 하게 됩니다.

 

 

그럼 예제를 한번 보실까요??

 

<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
  case 'A': document.write("Good job<br />");
            break;
  case 'B': document.write("Pretty good<br />");
            break;
  case 'C': document.write("Passed<br />");
            break;
  case 'D': document.write("Not so good<br />");
            break;
  case 'F': document.write("Failed<br />");
            break;
  default:  document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>

 

결과가 아래처럼 나오면 맞는건가요? 여러분이 직접 한번 해보시고 말씀해주세요 ^___^ 

Entering switch block
Good job
Exiting switch block

 

 

 

이번에는 break문을 생략했을 때 어떻게 실행되는지 한번 알아보죠. 

 

<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
  case 'A': document.write("Good job<br />");
  case 'B': document.write("Pretty good<br />");
  case 'C': document.write("Passed<br />");
  case 'D': document.write("Not so good<br />");
  case 'F': document.write("Failed<br />");
  default:  document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>

 

결과는 아래처럼 나옵니다. 

Entering switch block
Good job
Pretty good
Passed
Not so good
Failed
Unknown grade
Exiting switch block

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_switch_case.htm 

 


오늘은 자바스크립트의 if문에 대해서 알아보도록 하겠습니다.

다른 프로그래밍 언어와 마찬가지로 자바도 if문, if-else문, 그리고 if-else if-..-..-else문을 지원합니다.

하나씩 차례대로 배워보죠. 

if 문

if문의 문법은 아래와 같습니다.

 

 

if (조건){
   조건이 참일때 실행되어야 할 문장
}

조건의 결과가 참인 경우에만 안쪽에 있는 문장을 실행시킵니다.

 

예제를 한번 보실까요??

<script type="text/javascript">
<!--
var age = 20;
if( age > 18 ){
   document.write("<b>Qualifies for driving</b>");
}
//-->
</script>

 

위 코드는 아래와 같은 결과를 보여주겠죠?? 

Qualifies for driving

 

다음은 if-else문을 한번 보겠습니다. 

if...else 문

if문에서 else만 추가된 거죠. 문법은 아래와 같습니다.

 

 

if (조건){
   조건이 참이면 실행될 문장
}else{
   조건이 거짓이면 실행될 문장
}

조건이 참이면 if내의 문장을 실행하고 거짓이면 else내의 문장을 실행합니다. 

 

 

예제를 보도록 하겠습니다. 

<script type="text/javascript">
<!--
var age = 15;
if( age > 18 ){
   document.write("<b>Qualifies for driving</b>");
}else{
   document.write("<b>Does not qualify for driving</b>");
}
//-->
</script>

 

아래처럼 결과가 나오는게 맞나요?? 맞습니다~ 

Does not qualify for driving

 

if...else if... 문

이것도 어렵지 않습니다. 그저 else를 여러개 붙여 놓은 거라고 보시면 됩니다. 문법부터 한번 보시죠. 

 

 

if (조건 1){
   조건 1이 참이면 실행되야 할 문장 - A
}else if (조건 2){
   조건 1이 거짓이고 2가 참이면 실행되야 할 문장 - B
}else if (조건 3){
   조건 1, 2가 모두 거짓이고 3이 참이면 실행되야 할 문장 - C
}else{
   조건 1, 2, 3이 모두 거짓이면 실행되야 할 문장 - D
}

위 문법을 말로 풀어쓰면 이렇게 되는겁니다.  

 

만약 조건1이 참이면 A를 진행하고 B, C, D는 실행하지 마세요.

만약 조건1이 거짓이고 조건2가 참이면 B만 실행하세요.

만약 조건 1과 2가 모두 거짓이고 조건3이 참이라면 C만 실행하세요.

만약 조건1, 2, 3 모두가 거짓이면 D를 실행하면 됩니다. 

 

예제를 한번 보시죠.
<script type="text/javascript">
<!--
var book = "maths";
if( book == "history" ){
   document.write("<b>History Book</b>");
}else if( book == "maths" ){
   document.write("<b>Maths Book</b>");
}else if( book == "economics" ){
   document.write("<b>Economics Book</b>");
}else{
  document.write("<b>Unknown Book</b>");
}
//-->
</script>

 

결과가 아래처럼 나오는게 맞는건지 여러분이 판단해 보세요. 

Maths Book

 

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_ifelse.htm