Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript 기초 Chapter 8 Part II

Similar presentations


Presentation on theme: "JavaScript 기초 Chapter 8 Part II"— Presentation transcript:

1 JavaScript 기초 Chapter 8 Part II
이 서식 파일은 그룹 환경에서 교육 자료를 프레젠테이션할 때 시작 파일로 사용할 수 있습니다. 구역 구역을 추가하려면 슬라이드를 마우스 오른쪽 단추로 클릭하십시오. 구역을 사용하면 슬라이드를 쉽게 구성할 수 있으며, 여러 작성자가 원활하게 협력하여 슬라이드를 작성할 수 있습니다. 메모 설명을 제공하거나 청중에게 자세한 내용을 알릴 때 메모를 사용합니다. 프레젠테이션하는 동안 프레젠테이션 보기에서 이러한 메모를 볼 수 있습니다. 글꼴 크기에 주의(접근성, 가시성, 비디오 테이프 작성, 온라인 재생 등에 중요함) 배색 그래프, 차트 및 텍스트 상자에 특히 주의를 기울이십시오. 참석자가 흑백이나 회색조로 인쇄할 경우를 고려해야 합니다. 테스트로 인쇄하여 흑백이나 회색조로 인쇄해도 색에 문제가 없는지 확인하십시오. 그래픽, 테이블 및 그래프 간결하게 유지하십시오. 가능한 일관되고 혼란스럽지 않은 스타일과 색을 사용하는 것이 좋습니다. 모든 그래프와 표에 레이블을 추가합니다. Chapter 8 Part II

2 프로그래밍 언어의 요소 상수와 변수 연산자 배열 조건문 반복문(loop) 함수(function), 객체(class)
정수형/실수형: 1, 123, -5, 1.0, -1.2 문자형: “a”, “My Name is” Boolean: true, false 연산자 +, -, *, /, % 배열 array=[1,2,3]; name=[“John”,”Sam”] 조건문 if, if-else, if-else if-else, switch 반복문(loop) for, while, do while 함수(function), 객체(class) 표준 입력 및 출력

3 자바스크립트 문법 C 언어와 매우 유사 문장의 끝에는 semi-colon(;) block 지정은 중괄호( { } ) 사용
주석은 // 또는 /* */

4 자바스크립트 주석(comment) // Change heading: document.getElementById("myH").innerHTML = "My First Page"; // Change paragraph: document.getElementById("myP").innerHTML = "My first paragraph."; /* The code below will change the heading with id = "myH" and the paragraph with id = "myP" in my web page: */ document.getElementById("myH").innerHTML = "My First Page"; document.getElementById("myP").innerHTML = "My first paragraph.";

5 출력 document.write() alert() confirm() innerHTML HTML 문서에 결과를 출력
경고 창 confirm() 확인 창 innerHTML DOM에서 문서의 내용을 교체할 때 사용

6 예제 – js-output.html <!DOCTYPE html> <html> <head>
<script> document.write("<h1>Welcome to the Javascript World!</h1>"); document.write("<h2>앞으로 고생 좀 많이 합시다.</h2>"); </script> </head>

7 예제 – js-output.html (계속)
<body> <h1>My First Web Page</h1> <p>My First Paragraph.</p> <h3 id="demo" style="background-color:cyan">Hi!</h3> <button onclick="alert('This is ALERT!!! 경고');"> ALERT</button> <button onclick="confirm('Are you sure?');"> CONFIRM</button> <button onmouseover="changeDemo();" onmouseout="resetDemo();"> 여기에 마우스를</button> <button onclick="writeNewMsg();">여기 클릭</button>

8 예제 – js-output.html(계속)
<script> function changeDemo() { document.getElementById("demo").innerHTML = "Hello. Welcome to My World!!!!!"; } function resetDemo() { document.getElementById("demo").innerHTML = "Hi!"; function writeNewMsg() { document.write("<h1>문서가 로드된 후에 document.write를 사용하면 새로운 페이지가 열려요.</h1>") </script> </body> </html>

9 변수 변수(variable)는 데이터를 저장하는 상자 var 키워드를 사용하여서 선언(declare)한다.

10 변수의 타입 숫자형 변수 문자형 변수 Boolean: true 또는 false의 값을 가지는 변수
자바스크립트에서는 정수형, 실수형을 구분하지 않는다. var a,b; // 변수만 선언 var a=1, b=5.0; // 변수 선언과 값 지정 동시에 s=a+b; // var 선언 없이 사용도 가능하다 // +는 덧셈 문자형 변수 var a,b; var a=“Computer ”, b=“Engineering”; s=a+b; // 문자열에서 +은 붙이기 Boolean: true 또는 false의 값을 가지는 변수 var result = true; result=false;

11 js-variables.html <!doctype html> <body> <script>
var a=3; var name="Computer"; var bool=(3>4); document.write("a = " + a); document.write("<br>"); document.write("name = " + name); document.write("bool = " + bool); </script> </body>

12 연산자 문자형 변수에서의 덧셈(+) 연산자는 두 문자열을 합친다. a=“Computer ”; b=“Engineeing”;
dept=a+b;  dept=“ComputerEngineering”이 된다.

13 js-number.html <!doctype html> <html> <body>
<script> var a=31, b=5; document.write("a + b = " +(a+b) + "<br>"); document.write("a - b = " +(a-b) + "<br>"); document.write("a * b = " +(a*b) + "<br>"); document.write("a / b = " +(a/b) + "<br>"); document.write("a % b = " +(a%b) + "<br>"); // 31을 5로 나눈 나머지 document.write("a + b = " +a+b+ "<br>"); // 괄호에 조심하자… </script> </body> </html>

14 document.write()로 표 만들기
document.write()함수를 이용하여 출력할 때 HTML 문서 작성시와 같이 태그를 사용하여 출력한다.

15 js-table-1.html <!doctype html> <html> <head>
<style> td {width:50px} </style> </head> <body> <script> var colorR="#FF0000", colorG="#00FF00", colorB="#0000FF"; document.write("<table border=1 cellspacing=0>\n"); document.write("<tr>"); document.write("<td>"+colorR+"</td>"); document.write("<td style=background-color:"+colorR+"> </td>\n"); document.write("<td>"+colorG+"</td>"); document.write("<td style=background-color:"+colorG+"> </td>\n"); document.write("<td>"+colorB+"</td>"); document.write("<td style=background-color:"+colorB+"> </td>\n"); document.write("</tr>\n"); document.write("</table>"); </script> </body> </html>

16 엄청 긴 문자열 만들어 출력하기 자바스크립트로 한 요소(예: 테이블, 리스트 등)을 하나의 문자열로 만들어 출력하는 경우가 많다. var str=“”; // 빈 문자열 선언 str += “<ul>”; // += 연산자를 이용하여 문자열 합치기 str += “<li>리스트1</li>”; // str+=“A” --> str = str + “A” str += “<li>리스트2</li>”; str += “</ul>”; document.write(str); // 마지막에 str을 출력하면 리스트 완성

17 js-table-2.html 문자열 변수 table에 표만들기 소스 코드를 모두 모두 합쳐서 하나의 변수로 작성한 후, 출력
<!doctype html> <html> <head> <style> td {width:50px} </style> <script> function insertTable() { var table; var colorR="#F00", colorG="#0F0", colorB="#00F"; table = "<table border=1 cellspacing=0>\n"; table += "<tr>"; table += "<td>"+colorR+"</td>"; table += "<td style=background-color:"+colorR+"> </td>\n"; table += "<td>"+colorG+"</td>"; table += "<td style=background-color:"+colorG+"> </td>\n"; table += "<td>"+colorB+"</td>"; table += "<td style=background-color:"+colorB+"> </td>\n"; table += "</tr>\n"; table += "</table>"; document.getElementById("place").innerHTML=table; } </script> </head>

18 문자열을 생성하여 원하는 위치(요소)에 출력하기
아이디로 요소의 위치를 찾아 내용을 바꿀 수 있다. document.getElementById(“”).innerHTML=문자열

19 js-table-3.html <!doctype html> <html> <head>
<style> td {width:50px} </style> <script> function insertTable() { var table; var colorR="#FF0000", colorG="#00FF00", colorB="#0000FF"; table = "<table border=1 cellspacing=0>\n"; table += "<tr>"; table += "<td>"+colorR+"</td>"; table += "<td style=background-color:"+colorR+"> </td>\n"; table += "<td>"+colorG+"</td>"; table += "<td style=background-color:"+colorG+"> </td>\n"; table += "<td>"+colorB+"</td>"; table += "<td style=background-color:"+colorB+"> </td>\n"; table += "</tr>\n"; table += "</table>"; document.getElementById("place").innerHTML=table; }

20 js-table-3.html(계속) function hideTable() {
document.getElementById("place").innerHTML="없어졌지롱"; } </script> </head> <body> <h1>테이블을 만들어 봅시다.</h1> <p id=place>요기가 테이블 들어올 자리</p> <button onclick=insertTable()>Create Table</button> <button onclick=hideTable()>Hide Table</button> </body> </html>

21 제어문

22 조건문의 종류 if 문 if...else 문 switch 문

23 비교 연산자와 논리연산자 and: && or: || not: !

24 js-if.html <!doctype html> <html> <body>
<script> var msg = ""; var time = new Date().getHours(); if (time < 12) { // 12시 이전이면 msg = "Good Morning"; } else if (time < 18) { // 오후 6시 이전이면 msg = "Good Afternoon"; else { // 그렇지 않으면(오후 6시 이후이면) msg = "Good evening"; alert(msg); </script> </body> </html>

25 js-numberGame.html <html> <head>
<title></title> <script> var computerNumber; // 정답 var nGuesses = 0; // 추측 횟수 function createNumber() { computerNumber = Math.round(Math.random()*100); // 난수로 생성 document.getElementById("ans").innerHTML=computerNumber; } function guess() { var result = ""; // 결과 메시지 // 사용자가 입력한 값을 받아서 변수 number에 대입한다. var number = Number(document.getElementById("user").value); nGuesses++; // 추측 횟수를 증가시킨다. if (number == computerNumber) result = "성공입니다."; else if (number < computerNumber) result = "낮습니다."; else result = "높습니다."; document.getElementById("result").value = result; document.getElementById("guesses").value = nGuesses; </script> </head>

26 js-numberGame.html(계속)
<body onload=createNumber()> <h2>숫자 맞추기 게임</h2> 이 게임은 컴퓨터가 생성한 숫자를 맞추는 게임입니다. 숫자는 1부터 100 사이에 있습니다. <form> 숫자: <input type="text" id="user" size="5"> <input type="button" value="확인" onclick="guess();"> 추측횟수: <input type="text" id="guesses" size="5"> 힌트: <input type="text" id="result" size="16"> </form> <p id="ans" style="color:white"></p> </body> </html>

27 switch 문 switch(expression) { case 값1: statement1; break; case 값2:
default: statement3; }

28 사용 예 switch (new Date().getDay()) { case 0: day = "Sunday"; break;
day = "Monday"; case 2: day = "Tuesday"; case 3: day = "Wednesday"; case 4: day = "Thursday"; case 5: day = "Friday"; case 6: day = "Saturday"; }

29 예제 – js-switch.html <!doctype html> <html> <body>
<script> var grade = prompt("성적을 입력하시오:", "A-F사이의 문자로"); switch (grade) { case 'A': alert("잘했어요!"); break; case 'B': alert("좋은 점수군요"); case 'C': alert("괜찮은 점수군요"); case 'D': alert("좀더 노력하세요"); case 'F': alert("다음 학기 수강하세요"); default: alert("알 수 없는 학점입니다.") } </script> </body> </html>

30 반복문 같은 처리 과정을 여러 번 되풀이하는 것 for, while문이 있다.

31 while 문

32 <script> var i = 0; while (i < 10) { document.write("카운터 : "+i+"<br>"); i++; } </script>

33 for 문

34 <script> for (i = 0; i < 10; i++) { document.write("카운터 : "+i+"<br>"); } </script>

35 예제- js-for.html <!doctype html> <body> <script>
for(i=1; i<=6; i++) { document.write("<h"+i+">"); document.write("This is Heading"+i+"."); document.write("</h"+i+">"); } </script> </body>

36 nested for loop for loop안에 또 for loop를 사용하는 것을 nested loop(중첩 for문)이라고 한다. for(i=0; i<10; i++) { for(j=0; j<10; j++) { }

37 js-nestedloop.html <html> <head> <style>
table,td {border:1px solid black;;border-collapse:collapse} td {width:50px} </style> </head> <body> <script> document.write("<h1>표 만들기</h1>"); document.write("<table>"); var k=1; for (var i = 1; i <= 5; i++) { document.write("<tr>"); for (var j = 1; j <= 7; j++) { document.write("<td>" + (k++) + "</td>"); } document.write("</tr>"); document.write("</table>"); </script> </body>

38 배열 많은 값을 저장할 수 있는 공간이 필요할 때 배열을 사용한다. 서로 관련된 데이터를 차례로 접근하여서 처리할 수 있다.

39 배열을 생성하는 2가지 방법 리터럴로 배열 생성 Array 객체로 배열 생성
var fruits = ["apple", "banana", "peach"]; Array 객체로 배열 생성 var fruits=new Array(“apple",“banana",“orange“);

40 예제 – js-array.html <!DOCTYPE html> <html> <body>
<script> var i; var fruits = new Array(); fruits[0] = "Apple"; fruits[1] = "Banana"; fruits[2] = "Orange"; for (i = 0; i < fruits.length; i++) { document.write(fruits[i] + "<br>"); } </script> </body> </html>

41 함수 함수는 입력을 받아서 특정한 작업을 수행하여서 결과를 반환하는 블랙 박스

42 예제 – js-function.html <!DOCTYPE html> <html> <head>
<script> function showDialog() { alert("안녕하세요?"); } </script> </head> <body> <button onclick="showDialog()">대화상자오픈</button> </body> </html>

43 인수와 매개 변수 <!DOCTYPE html> <html> <head>
<script> function greeting(name, position) { alert(name + " " + position + "님을 환영합니다."); } </script> </head> <body> <button onclick="greeting('홍길동', '부장')">눌러보세요!</button> </body> </html>

44 함수의 반환값 return 문장을 사용하여 외부로 값을 반환

45 지역변수와 전역변수 변수는 프로그램이 실행중 저장 공간으로 사용되고 프로그램이 종료하면 없어진다.
지역변수는 함수가 호출되어 실행될때 사용되고 함수의 호출이 끝나면 소멸된다. 전역변수는 프로그램 어디에서나 사용할 수 있는(값의 지정이 가능한) 변수이다. 함수 외부에서 변수 선언한다.

46 Js-global.html <!doctype html> <body> <script>
var number=0; document.write("<p>처음에는 number is "+number+"</p>"); function myFunction1() { var number=20; document.write("<p>함수1에서는 number is "+number+"</p>"); } myFunction1(); document.write("<p>함수1 호출이 끝나고 난 후에는 number is "+number+"</p>"); function myFunction2() { number=40; document.write("<p>함수2에서는 number is "+number+"</p>"); myFunction2(); document.write("<p>함수2 호출이 끝나고 난 후에는 number is "+number+"</p>"); </script> </body>

47

48


Download ppt "JavaScript 기초 Chapter 8 Part II"

Similar presentations


Ads by Google