AR삽질러

유수봉 교수의 WEB-10주차 본문

WEB/유수봉교수의 WEB

유수봉 교수의 WEB-10주차

아랑팡팡 2023. 5. 10. 16:41
728x90

유수봉 교수의 WEB(객체)

 

1. 객체(Object)란?

 JavaScript는 object기반의 스크립트 언어이며 자바스크립트를 이루고 있는 거의 "모든것"이 객체이다. Primitives을 제외한 나머지 값을(함수, 배열, 정규표현식 등)은 모두 객체이다.

 

 JavaScript의 객체는 key : value 로 구성된 Property들의 집합이다. 프로퍼티의 값으로 자바스크립트에서 사용할 수 있는 모든 값들을 사용할 수 있다. JavaScript의 함수는 일급 객체이므로 값으로 취급할 수 있다. 따라서 Property값으로 함수를 사용할 수도 있으며 Property value가 함수일 경우 일반 함수와 구분하기 위해 메소드라고 부른다.

 

2. Core Objects

- 자바스크립트 언어가 실행되는 어디서나 사용 가능한 기본객체

- 기본 객체로 표준객체

- Array, Date, String, Math타입 등

- 웹 페이지 자바스크립트 코드에서 혹은 서버에서 사용 가능하다.

 

▶ 객체의 생성 - js0701.html

 

<!DOCTYPE html>
<html>

<head>
    <title>객체 생성 및 활용</title>
</head>

<body>
    <h3>객체 생성 및 활용</h3>
    <hr>
    <script>
        var today = new Date();

        document.write("현재시간 : " + today.toGMTString() + "<br>");

        // String 객체 생성
        var mystr = new String("자바스크립트 공부하기");
        document.write("mystr의 내용 : " + mystr + "<br>");
        document.write("mystr의 길이 : " + mystr.length + "<br>");
    </script>

</body>

</html>

 

3. 배열 Array

JavaScript - Objects

Array

 - 여러개의 원소들을 연속적으로 저장한다.

 - 전체를 하나의 단위로 다루는 데이터 구조

Array생성Ex

배열을 만드는 방법

 - [ ] 로 배열생성

 - Array() 객체로 배열 생성

 

▶ 객체의 활용 - js0702.html

<!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(n=0; n<5; n++) {
		var size = plots[n]; // plots 배열의 n번째 원소
		while(size>0) {
			document.write("*");
			size--;
		}
		document.write(plots[n] + "<br>");
	}
</script>
</body>
</html>

초기값을 가진 배열 생성

 - 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

 

배열의 원소 개수, length프로퍼티

length 프로퍼티의 조정

 - plots.length = 10 // plots의 크기는 5에서 10으로 늘어난다.

 - plots.length = 2; // plots의 크기는 2로 줄고, 2개 이외의 원소는 삭제된다.

 

4. AttributeProperty의 차이점

 JS 에서 AttributeHTML 문서 안에, PropertyHTML DOM tree 안에 있는 것이다.
 이 의미는 Attribute는 변하지 않지만 Property는 변할 수 있다는 뜻.
Attribute?
 - AttributeHTML elements추가적인 정보를 넣을 때 사용되는 요소이다.
- <div class="my-class"></div>
- 위의 예시에서 class는 속성(attribute)이고, my-class는 속성값(value)이 된다.
Property?
- Propertyhtml DOM tree 안에서 attribute가르키는 요소이다.
- Our DIV node
- |- nodename = "DIV"
- |- className = "my-class"
- |- style

 

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>
<script>
	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>

 

자바스크립트 코어 객체와 배열-2

1. 코어객체

 코어 객체 종류

 - Array, Date, String, Math등

 - Property-> 값 : Date's Properties, Year, Month, Day, Weeks..

 - Method -> 함수 : .now(), getTime(), setTime()..

 

코어 객체 생성

 - new 키워드 이용

2. Date 객체

 - 시간 정보를 담는 객체

 - 현재 시간 정보

  var now = new Date(); // 현재날짜와 시간(시, 분, 초)값으로 초기화된 객체 생성

 - 학기 시작일 2023년 5월 10일의 날짜 기억

 var startDay = new Date(2023, 5, 10); // 2023년 5월 19일

 

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() + 1 + "월<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>

 

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>

 

3. String 객체

 - 문자열을 담기 위한 객체

 - String객체는 일단 생성되면 수정 불가

4. Math 객체

 - 수학 계산을 위한 프로퍼티와 메소드 제공

 - new Math()로 객체 생성하지 않고 사용

난수발생

 - Math.rendom() : 0 ~ 1 보다 작은 랜덤한 실수를 리턴

 - Math.floor(m)은 m의 소수점 이하를 제거한 정수 리턴

7–8 Math를 이용한 구구단 연습

<!DOCTYPE html>
<html>
<head><title>Math를 활용한 구구단 연습</title>
<script>		 // 1~9의 십진 난수 리턴
  function randomInt() { 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>");
		}
	</script>
</body>
</html>

사용자 객체 만들기

 - 사용자가 새로운 타입의 객체를 작성가능

 - 새로운 타입의 객체를 만드는 2가지 방법 : new Object(), 리터럴 표기

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; }, 	// 입금. 잔고 증가
	withdraw : function (money) { 			// 출금, money는 출금 액수
		this.balance -= money; 
		return money;
	} 
};
</script>
</head>
<body>
<h3>리터럴 표기법으로 사용자 객체 만들기</h3>
<hr>
<script>
	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>

 

자기 홈페이지에 날짜와시간이 표시되도록 구현

 

728x90
반응형
LIST