Presentation is loading. Please wait.

Presentation is loading. Please wait.

명품 웹 프로그래밍.

Similar presentations


Presentation on theme: "명품 웹 프로그래밍."— Presentation transcript:

1 명품 웹 프로그래밍

2 강의 목표 객체의 기본 개념을 간단히 이해한다. 브라우저가 제공하는 기본 객체(코어 객체)들의 종류를 알고 사용할 수 있다.
Date 객체를 활용할 수 있다. String 객체를 활용할 수 있다. 자바스크립트 배열을 만들 수 있다. Array 객체를 이용하여 배열을 만들고 활용할 수 있다. Math 객체를 활용할 수 있다.

3 객체 개념 현실 세계는 객체들의 집합 사람, 책상, 자동차, TV 등 객체는 자신만의 고유한 구성 속성
자동차 : <색상:오렌지, 배기량:3000CC, 제조사:한성, 번호:서울1- 1> 사람 : <이름:이재문, 나이:20, 성별:남, 주소:서울> 은행 계좌 : <소유자:황기태, 계좌번호:111, 잔액:35000원>

4 자바스크립트 객체 자바스크립트 객체 구성 여러 개의 프로퍼티(property)와 메소드로 구성 프로퍼티 : 객체의 고유한 속성
메소드(method) : 함수 owner “황기태” var account = { owner : "황기태", code : "111", balance : , deposit : function() { … }, withdraw : function() { … }, inquiry : function() { … } }; code “111” 프로퍼티 balance 35000 deposit() inquiry() 메소드 withdraw() account 객체를 만드는 자바스크립트 코드 자바스크립트 객체 account

5 자바스크립트 객체 종류 자바스크립트는 객체 기반 언어 자바스크립트 객체의 유형 자바스크립트는 객체 지향 언어 아님
1. 코어 객체 자바스크립트 언어가 실행되는 어디서나 사용 가능한 기본 객체 기본 객체로 표준 객체 Array, Date, String, Math 타입 등 웹 페이지 자바스크립트 코드에서 혹은 서버에서 사용 가능 2. HTML DOM 객체 HTML 문서에 작성된 각 HTML 태그들을 객체화한 것들 HTML 문서의 내용과 모양을 제어하기 위한 목적 W3C의 표준 객체 3. 브라우저 객체 자바스크립트로 브라우저를 제어하기 위해 제공되는 객체 BOM(Brower Object Model)에 따르는 객체들 비표준 객체

6 코어 객체 코어 객체 종류 코어 객체 생성 객체 접근 Array, Date, String, Math 등 new 키워드 이용
객체가 생성되면 객체 내부에 프로퍼티와 메소드들 존재 객체 접근 객체와 멤버 사이에 점(.) 연산자 이용 var today = new Date(); // 시간 정보를 다루는 Date 타입의 객체 생성 var msg = new String(“Hello”); // “Hello” 문자열을 담은 String 타입의 객체 생성 obj.프로퍼티 = 값; // 객체 obj의 프로퍼티 값 변경 변수 = obj.프로퍼티; // 객체 obj의 프로퍼티 값 알아내기 obj.메소드(매개변수 값들); // 객체 obj의 메소드 호출

7 예제 7–1 자바스크립트 객체 생성 및 활용 <!DOCTYPE html> <html>
<head><title>객체 생성 및 활용</title></head> <body> <h3>객체 생성 및 활용</h3> <hr> <script> // Date 객체 생성 var today = new Date(); // Date 객체의 toGMTString() 메소드 호출 document.write("현재 시간 : " + today.toGMTString() + "<br>"); // String 객체 생성 var mystr= new String("자바스크립트 공부하기"); document.write("mystr의 내용 : " + mystr + "<br>"); document.write("mystr의 길이 : " + mystr.length + "<br>"); // mystr.length=10; // 이 문장은 오류이다. </script> </body> </html> 객체 생성 메소드 호출 프로퍼티 읽기

8 자바스크립트 배열 배열 배열 생성 사례 여러 개의 원소들을 연속적으로 저장 전체를 하나의 단위로 다루는 데이터 구조
0에서 시작하는 인덱스를 이용하여 배열의 각 원소 접근 var cities = [“Seoul”, “New York”, “Paris”]; var n = [4, 5, -2, 28, 33]; cities “Seoul” “New York” “Paris” n cities[0] 4 5 -2 28 33 cities[1] n[0] n[1] n[2] n[3] n[4] cities[2] var name = cities[0]; // name은 “Seoul” cities[1] = “Gainesville”; // “New York” 자리에 “Gainesville” 저장

9 자바스크립트에서 배열을 만드는 방법 배열 만드는 2가지 방법 []로 배열 만들기 Array 객체로 배열 만들기
[] 안에는 원소들의 초기 값 나열 배열 크기 배열의 크기는 고정되지 않고, 마지막 원소 추가 시 늘어남 var week = [“월”, “화”, “수”, “목”, “금”, “토”, “일”]; var plots = [-20, -5, 0, 15, 20]; plots[5] = 33; // plots 배열에 6번째 원소 추가. 배열 크기는 6이 됨 plots[6] = 22; // plots 배열에 7번째 원소 추가. 배열 크기는 7이 됨 plots[10] = 33; // 오류. 인덱스 10은 plots 배열의 영역을 벗어났음

10 예제 7-2 []로 배열 만들기 <!DOCTYPE html>
<html><head><title>[]로 배열 만들기</title></head> <body> <h3>[]로 배열 만들기</h3> <hr> <script> var plots = [20, 5, 8, 15, 20]; // 원소 5개의 배열 생성 document.write("var plots = [20, 5, 8, 15, 20]<br>"); for(i=0; i<5; i++) { var size = plots[i]; // plots 배열의 i번째 원소 while(size>0) { document.write("*"); size--; } document.write(plots[i] + "<br>"); </script> </body> </html>

11 Array로 배열 만들기 초기 값을 가진 배열 생성 초기화되지 않은 배열 생성 빈 배열 생성
일정 크기의 배열 생성 후 나중에 원소 값 저장 빈 배열 생성 원소 개수를 예상할 수 없는 경우 var week = new Array(“월”, “화”, “수”, “목”, “금”, “토”, “일”); var week = new Array(7); // 7개의 원소를 가진 배열 생성 week[0] = “월”; week[1] = “화”; ... week[6] = “일”; var week = new Array(); // 빈 배열 생성 week[0] = “월”; // 배열 week 크기 자동으로 1 week[1] = “화”; // 배열 week 크기 자동으로 2

12 배열의 원소 개수, length 프로퍼티 배열의 크기 : Array 객체의 length 프로퍼티
var plots = [-20, -5, 0, 15, 20]; var week = new Array(“월”, “화”, “수”, “목”, “금”, “토”, “일”); var m = plots.length; // m은 5 var n = week.length; // n은 7 plots.length = 10; // 오류. length는 읽기 전용 프로퍼티

13 예제 7-3 Array 객체로 배열 만들기 <!DOCTYPE html>
<html><head><title>Array 객체로 배열 만들기</title></head> <body> <h3>Array 객체로 배열 만들기</h3> <hr> <script> var degrees = new Array(); // 빈 배열 생성 degrees[0] = 15.1; degrees[1] = 15.4; degrees[2] = 16.1; degrees[3] = 17.5; degrees[4] = 19.2; degrees[5] = 21.4; var sum = 0; for(i=0; i<degrees.length; i++) sum += degrees[i]; document.write("평균 온도는 " + sum/degrees.length + "<br>"); </script> </body> </html> 배열 크기만큼 루프 배열 degrees의 크기, 6

14 배열의 특징 배열은 Array 객체 배열에 여러 타입의 데이터 섞여 저장 가능 []로 생성해도 Array 객체로 다루어짐
var any = new Array(5); // 5개의 원소를 가진 배열 생성 any[0] = 0; any[1] = 5.5; any[2] = “이미지 벡터”; // 문자열 저장 any[3] = new Date(); // Date 객체 저장 any[4] = convertFunction; // function convertFunction()의 주소 저장

15 예제 7–4 Array 객체의 메소드 활용 <!DOCTYPE html>
<html><head><title>Array 객체의 메소드 활용</title> <script> function pr(msg, arr) { document.write(msg + arr.toString() + "<br>"); } </script> </head> <body> <h3>Array 객체의 메소드 활용</h3> <hr> var a = new Array("황", "김", "이"); var b = new Array("박"); var c; pr("배열 a = ", a); pr("배열 b = ", b); document.write("<hr>"); c = a.concat(b); // c는 a와 b를 연결한 새 배열 pr("c = a.concat(b)후 c = ", c); pr("c = a.concat(b)후 a = ", a); c = a.join("##"); // c는 배열 a를 연결한 문자열 pr("c = a.join() 후 c = ", c); pr("c = a.join() 후 a = ", a); c = a.reverse(); // a.reverse()로 a 자체 변경. c는 배열 pr("c= a.reverse() 후 c = ", c); pr("c= a.reverse() 후 a = ", a); c = a.slice(1, 2); // c는 새 배열 pr("c= a.slice(1, 2) 후 c = ", c); pr("c= a.slice(1, 2) 후 a = ", a); c = a.sort(); // a.sort()는 a 자체 변경. c는 배열 pr("c= a.sort() 후 c = ", c); pr("c= a.sort() 후 a = ", a); c = a.toString(); // toString()은 원소 사이에 ","를 넣어 문자열 생성 document.write("a.toString() : " + c); // c 는 문자열 </script></body></html>

16 Date 객체 Date 객체 Date 객체 활용 시간 정보를 담는 객체 현재 시간 정보
학기 시작일 2017년 3월 1일의 날짜 기억 Date 객체 활용 var now = new Date(); // 현재 날짜와 시간(시, 분, 초) 값으로 초기화된 객체 생성 var startDay = new Date(2017, 2, 1); // 2017년 3월 1일(2는 3월을 뜻함) var now = new Date(); // 현재 2017년 5월 15일 저녁 8시 48분이라면 var date = now.getDate(); // 오늘 날짜. date = 15 var hour = now.getHours(); // 지금 시간. hour = 20

17 예제 7–5 Date 객체 생성 및 활용 <!DOCTYPE html> <html> <head>
<title>Date 객체로 현재 시간 알아내기</title> </head> <body> <h3>Date 객체로 현재 시간 알아내기</h3> <hr> <script> var now = new Date(); // 현재 시간 값을 가진 Date 객체 생성 document.write("현재 시간 : " + now.toUTCString() + "<br><hr>"); document.write(now.getFullYear() + "년도<br>"); document.write(now.getMonth() "월<br>"); document.write(now.getDate() + "일<br>"); document.write(now.getHours() + "시<br>"); document.write(now.getMinutes() + "분<br>"); document.write(now.getSeconds() + "초<br>"); document.write(now.getMilliseconds() + "밀리초<br><hr>"); var next = new Date(2017, 7, 15, 12, 12, 12); // 7은 8월 document.write("next.toLocaleString() : " + next.toLocaleString() + "<br>"); </script> </body> </html>

18 예제 7–6 방문 시간에 따라 변하는 배경색 만들기 <!DOCTYPE html> <html>
<head> <title>방문 시간에 따라 변하는 배경색</title> </head> <body> <h3>페이지 방문 초시간이 짝수이면 violet, 홀수이면 lightskyblue 배경</h3> <hr> <script> var current = new Date(); // 현재 시간을 가진 Date 객체 생성 if(current.getSeconds() % 2 == 0) document.body.style.backgroundColor = "violet"; else document.body.style.backgroundColor = "lightskyblue"; document.write("현재 시간 : "); document.write(current.getHours(), "시,"); document.write(current.getMinutes(), "분,"); document.write(current.getSeconds(), "초<br>"); </script> </body> </html>

19 String 객체 String 문자열을 담기 위한 객체 String 객체는 일단 생성되면 수정 불가능
var hello = new String(“Hello”); var hello = “Hello”; “Hello” hello 객체 charAt() concat() split() slice() replace() var hello = new String(“Hello”); var res = hello.concat(“Javascript”); // concat() 후 hello의 문자열 변화 없음 “Hello” hello 객체 “HelloJavascript” res 객체

20 String 객체의 특징 문자열 길이 문자열을 배열처럼 사용 String 객체의 length 프로퍼티 : 읽기 전용
[] 연산자를 사용하여 각 문자 접근 var hello = new String(“Hello”); var every = “Boy and Girl”; var m = hello.length; // m은 5 var n = every.length; // n은 12 var n = "Thank you".length; // n은 9 var hello = new String("Hello"); var c = hello[0]; // c = "H". 문자 H가 아니라 문자열 “H”

21 예제 7–7 String 객체의 메소드 활용 <!DOCTYPE html>
<html><head><title>String 객체의 메소드 활용</title></head> <body> <h3>String 객체의 메소드 활용</h3> <hr> <script> var a = new String("Boys and Girls"); var b = "!!"; document.write("a : " + a + "<br>"); document.write("b : " + b + "<br><hr>"); document.write(a.charAt(0) + "<br>"); document.write(a.concat(b, "입니다") + "<br>"); document.write(a.indexOf("s") + "<br>"); document.write(a.indexOf("And") + "<br>"); document.write(a.slice(5, 8) + "<br>"); document.write(a.substr(5, 3) + "<br>"); document.write(a.toUpperCase() + "<br>"); document.write(a.replace("and", "or") + "<br>"); document.write(" kitae ".trim() + "<br><hr>"); var sub = a.split(" "); document.write("a를 빈칸으로 분리<br>"); for(var i=0; i<sub.length; i++) document.write("sub" + i + "=" + sub[i] + "<br>"); document.write("<hr>String 메소드를 실행 후 a와 b 변함 없음<br>"); document.write("b : " + b + "<br>"); </script> </body> </html> a.charAt(0) a.indexOf("s") a.slice(5,8)

22 Math 객체 Math 수학 계산을 위한 프로퍼티와 메소드 제공 new Math()로 객체 생성하지 않고 사용 난수 발생
Math.random() : 0~1보다 작은 랜덤한 실수 리턴 Math.floor(m)은 m의 소수점 이하를 제거한 정수 리턴 var sq = Math.sqrt(4); // 4의 제곱근을 구하면 2 var area = Math.PI*2*2; // 반지름이 2인 원의 면적 // 0~99까지 랜덤한 정수를 10개 만드는 코드 for(i=0; i<10; i++) { var m = Math.random()*100; // m은 0~ 보다 작은 실수 난수 var n = Math.floor(m); // m에서 소수점 이하를 제거한 정수(0~99사이) document.write(n + " "); }

23 예제 7–8 Math를 이용한 구구단 연습 <!DOCTYPE html> <html>
<head><title>Math를 활용한 구구단 연습</title><script> function randomInt() { // 1~9의 십진 난수 리턴 return Math.floor(Math.random()*9) + 1; } </script> </head> <body> <h3>Math를 활용한 구구단 연습</h3> <hr> <script> // 구구단 문제 생성 var ques = randomInt() + "*" + randomInt(); // 사용자로부터 답 입력 var user = prompt(ques + " 값은 얼마입니까?", 0); if(user == null) { // 취소 버튼이 클릭된 경우 document.write("구구단 연습을 종료합니다"); else { var ans = eval(ques); // 구구단 정답 계산 if(ans == user) // 정답과 사용자 입력 비교 document.write("정답! "); else document.write("아니오! "); document.write(ques + "=" + "<strong>" + ans + "</strong>입니다<br>"); </body> </html>

24 사용자 객체 만들기 사용자가 새로운 타입의 객체 작성 가능 새로운 타입의 객체 만드는 2 가지 방법만 소개
new Object() 이용 리터럴 표기법 이용 은행 계좌를 표현하는 account 객체 deposit() withdraw() 자바스크립트 객체 account 프로퍼티 메소드 code balance owner “111” 35000 “황기태” inquiry()

25 예제 7-9 new Object()로 계좌를 표현하는 account 객체 만들기
<!DOCTYPE html> <html><head><title>new Object()로 사용자 객체 만들기</title> <script> //메소드로 사용할 3 개의 함수 작성 function inquiry() { return this.balance; } // 잔금 조회 function deposit(money) { this.balance += money; } // money 만큼 저금 function withdraw(money) { // 예금 인출, money는 인출하고자 하는 액수 // money가 balance보다 작다고 가정 this.balance -= money; return money; } // 사용자 객체 만들기 var account = new Object(); account.owner = "황기태"; // 계좌 주인 프로퍼티 생성 및 초기화 account.code = "111"; // 코드 프로퍼티 생성 및 초기화 account.balance = 35000; // 잔액 프로퍼티 생성 및 초기화 account.inquiry = inquiry; // 메소드 작성 account.deposit = deposit; // 메소드 작성 account.withdraw = withdraw; // 메소드 작성 </script></head> <body> <h3>new Object()로 사용자 객체 만들기</h3> <hr> // 객체 활용 document.write("account : "); document.write(account.owner + ", "); document.write(account.code + ", "); document.write(account.balance + "<br>"); account.deposit(10000); // 10000원 저금 document.write("10000원 저금 후 잔액은 " + account.inquiry() + "<br>"); account.withdraw(5000); // 5000원 인출 document.write("5000원 인출 후 잔액은 " + account.inquiry() + "<br>"); </script> </body></html> this.balance는 객체의 balance 프로퍼티

26 예제 7-10 리터럴 표기법으로 계좌를 표현하는 account 객체 만들기
<!DOCTYPE html> <html> <head><title>리터럴 표기법으로 사용자 객체 만들기</title> <script> //사용자 객체 만들기 var account = { // 프로퍼티 생성 및 초기화 owner : "황기태", // 계좌 주인 code : "111", // 계좌 코드 balance : 35000, // 잔액 프로퍼티 // 메소드 작성 inquiry : function () { return this.balance; }, // 잔금 조회 deposit : function(money) { this.balance += money; }, // 저금. money 만큼 저금 withdraw : function (money) { // 예금 인출, money는 인출하고자 하는 액수 // money가 balance보다 작다고 가정 this.balance -= money; return money; } }; </script></head> <body> <h3>리터럴 표기법으로 사용자 객체 만들기</h3> <hr> document.write("account : "); document.write(account.owner + ", "); document.write(account.code + ", "); document.write(account.balance + "<br>"); account.deposit(10000); // 10000원 저금 document.write("10000원 저금 후 잔액은 " + account.inquiry() + "<br>"); account.withdraw(5000); // 5000원 인출 document.write("5000원 인출 후 잔액은 " + account.inquiry() + "<br>"); </script> </body></html>


Download ppt "명품 웹 프로그래밍."

Similar presentations


Ads by Google