티스토리 뷰

자바스크립트 또한 다른 언어와 비슷하게 if, for, while 등 거의 대부분의 제어문을 사용할 수 있다.

 

간단한 예제 몇개를 작성해보며 알아보자.


1. if

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>if example</title>
	<link rel = "stylesheet" href = "css/even.css"/>
</head>
<body>
	<script>
		var n = prompt("숫자를 입력해주세요.");
		var bool = null;
		if(n % 3 == 0){
			bool = confirm("해당 숫자는 3의 배수입니다. 계속하시겠습니까?");
		} else {
			bool = confirm("해당 숫자는 3의 배수가 아닙니다. 계속하시겠습니까?");
		} 
		if(bool){
			location.href = "even.html";
		} else{
			alert("아 Holy Moly~");
		}
	</script>
</body>
</html>

2. for

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Insert title here</title>
	<link rel = "stylesheet" href = "css/gugudan.css"/>
</head>
<body>
	<h1>구구단</h1>
	<script>
		for(var i = 1; i < 10; i++){
			document.write("<div>");
			document.write(i + "단 <br/>");
			for(var j = 1; j < 10; j++){
				var mul = i*j;
				document.write(i + "x" + j + "=" + mul + "<br />");
			}
			document.write("</div>");
		}
	</script>
</body>
</html>

3. switch - case

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Insert title here</title>
	<link rel = "stylesheet" href = "css/switch.css">
</head>
<body>
	<script>
		var session = prompt("관심 세션 선택: 1 - 마케팅, 2 - 개발, 3 - 디자인", "1");
		
		switch(session) {
		case "1":
			document.write("<p>마케팅 세션 <strong>201호</strong>에서 진행</p>");
			break;
		case "2":
			document.write("<p>개발 세션 <strong>401호</strong>에서 진행</p>");
			break;
		case "3":
			document.write("<p>디자인 세션 <strong>301호</strong>에서 진행</p>");
			break;
		default:
			alert("잘못 입력했습니다.");
		}
	</script>
</body>
</html>

4. while

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>while을 사용한 간단한 팩토리얼</title>
<link rel="stylesheet" href="css/factorial.css" />
</head>
<body>
	<script>
		var n = prompt("숫자를 입력해주세요.");
		var nFact = 1;

		var i = 2;
		while (i <= n) {
			nFact *= i;
			i++;
		}

		document.write(nFact);
	</script>
</body>
</html>

각각의 제어문의 사용 방법을 익히기 위한 예시이므로, 따로 css코드나 결과 페이지는 설명하지 않는다.

Comments