JavaScript - Object 객체, DOM

|
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>0909실습</title>
<script type="text/Javascript">

/*문제1*/
/*
function Stack(){ // stack 생성자 함수
	this.stack = [];
	this.top = 0;
	this.push = push;
	this.pop = pop;
	this.peek = peek;
	this.isEmpty = isEmpty;
	this.size = size;
	this.print = print;
}

function size(){
	return this.top;
}

function isEmpty(){
	return (this.stack.length == null);
}

function push(a){
	this.stack[this.top++] = a; 
}

function peek(){
	return this.stack[this.top-1];
}

function pop(){
	this.stack[--this.top];
}

function print(){
	for(var i =0; i<this.top; i++){
		document.write(this.stack[i] + "<br>");
	}
}

function question1(){
	var stack = new Stack();
	console.log(stack.isEmpty()); // 결과는 true
	stack.push(5);
	stack.push(8);
	console.log(stack.peek()); // 결과는 8
	stack.push(11);
	console.log(stack.size()); // 결과는 3
	console.log(stack.isEmpty()); // 결과는 false
	stack.push(15);
	stack.pop();
	stack.pop();
	console.log(stack.size()); // 결과는 2
	stack.print(); // 결과는 5, 8
}
*/

/*문제2*/
/*
function Queue(){ // Queue 생성자 함수
	this.queue = [];
	this.front = 0;
	this.enqueue = enqueue; // 넣는것
	this.dequeue = dequeue; // 빼는 것
	this.isEmpty = isEmpty;
	this.size = size;
	this.print = print;
}  
 
function enqueue(a){
	this.queue.push(a); 
}

function dequeue(){
	return this.queue.shift();
}

function front(){
	return this.queue[0];
}

function size(){
	return this.queue.length;
}

function isEmpty(){
	return (this.queue.length == 0); // null로 하면 결과 false로 나옴.
}

function print(){
		console.log(this.queue.toString());
}

function toString(){
	return this.queue.toString();
}

function question2(){
	var queue = new Queue();
	console.log(queue.isEmpty()); //결과는 true
	queue.enqueue("John");
	queue.enqueue("Jack");
	queue.print(); // 결과는 John,Jack
	queue.enqueue("Camila");
	queue.print(); // 결과는 John,Jack,Camila
	console.log(queue.size()); //결과는 3
	console.log(queue.isEmpty()); //결과는 false
	queue.dequeue();
	queue.dequeue();
	queue.print(); // 결과는 Camila
}
*/

/*문제3*/
function Set(){ // set 생성자 함수
	this.set = {};
	this.add = add; // 넣는것
	this.remove = remove; // 빼는 것
	this.has = has; // 존재여부확인
	this.size = size;
	this.values = values;
	this.clear = clear;
}  
 
function add(a){
	if(!this.has(a)){
		this.set[a] = a;
		return true;
	}
	return false;
}

function remove(a){
	if(this.has(a)){
		delete this.set[a];
		return true;
	}
	return false;
}

function clear(){
	this.set = {};
}

function size(){
	return Object.keys(this.set).length;
}

function has(a){
	return a in this.set; 
}

function values(){
	return this.set;
}

function union(otherSet){
	var unionSet = new Set();
	var values = this.values();
	for(var i=0; i<values.length; i++){
		unionSet.add(values[i]);
	}
	values = otherSet.values();
	for(var i =0; i<values.length; i++){
		unionSet.add(values[i]);
	}
	return unionSet;
}

function question3(){
	var set = new Set();
	set.add(1);
	console.log(set.values()); //결과는 ["1"]
	console.log(set.has(1));   //결과는 true
	console.log(set.size());   //결과는 1
	set.add(2);
	console.log(set.values()); //결과는 ["1", "2"]
	set.remove(1);
	console.log(set.values()); //결과는 ["2"]
	set.clear();
	console.log(set.values()); //결과는 []
	
	// Set에 union 메소드 추가하기
	var setA = new Set();
	setA.add(1);
	setA.add(2);
	setA.add(3);
	var setB = new Set();
	setB.add(3);
	setB.add(4);
	setB.add(5);
	setB.add(6);
	var unionAB = setA.union(setB); // set을 리턴
	console.log(unionAB.values());
}

/* Object 객체 예제*/
/* Object : 모든 객체가 가지고 있는 기본적인 형태. 아무것도 상속받지 않는 순수한 객체다. 자바스크립트에서는 값을 저장하는 기본적인 단위로 Object를 사용한다. 
//1. defineProperty()
var object = {};
Object.defineProperty(object, 'name', {
	value:'홍길동',  // 속성값
	writable:false, // 속성값 변경여부
	enumerable: true, // for in 문에 검색여부
	configurable: false // 속성설정 변경여부
});
object.name = 'OTHER';
console.log(object.name); // 위에서 OTHER로 했어도 홍길동으로 찍힘(writable:false)
for(var i in object){
	console.log(i + ':' + object[i]); // true로 해야 찍힘
}

//1-2. defineProperties():한번에 여러 개의 property 추가
var object2 = {};
Object.defineProperties(object2, {
	name: {value:'김길동'},
	region: {value:'서울특별시'}
});

//2. get, set
var object3 = {};
var value='test';
Object.defineProperty(object3, 'name', {
	get:function(){  // value 리턴
		console.log("getter");
		return value;
	},
	set:function(newValue){   // 새로들어온값 set
		console.log("setter");
		value = newValue;
	}
});
object3.name = 'ALPHA'; // setter 호출
console.log(object3.name); // getter 호출 -> ALPHA

//3. create : 기존의 객체를 복제하고 새로운 속성을 추가하여 객체생성
// 빈 객체를 기반으로 name, region 속성을 추가하여 객체생성
var object4 = Object.create({}, {
	name: {value:'김길동', enumerable: true},
	region: {value:'서울특별시', enumerable: true},
});
console.log(Object.keys(object4)); // (2) ["name", "region"]
var person = Object.create({}, {
	gender: {value:'남자', enumerable: true},
	hobby: {value:'기타', enumerable: true},
});
console.log(Object.keys(person)); // ["gender", "hobby"]

//4. hasOwnProperty : 해당 객체의 소속인지를 체크해 볼수 있음.
// 인자로 전달된 속성의 이름이 객체의 속성인지 여부를 판단.
function Dog(color, name, age, family){
	this.color = color;
	this.name = name;
	this.age = age;
	this.family = family;
	this.breed = function(){
		return this.color + " " + this.family;
	}
}
var myDog = new Dog("검정색", "곰", 3, "불독");
myDog.hasOwnProperty("color"); // true
myDog.hasOwnProperty("class"); // 상속받은 프로퍼티 이므로, false를 반환함.

//5. propertyIsEnumerable : hasOwnProperty()가 true이면서 열거가능
function Dog(color, name, age){
	this.color = color;
	this.name = name;
	this.age = age;
}
var myDog = new Dog("흰색", "마루", 1); // color 프로퍼티의 enumerable 속성을 false로 설정함.
Object.defineProperty(myDog, 'color', {enumerable: false});
myDog.propertyIsEnumerable("color"); // false
myDog.propertyIsEnumerable("name"); // true

// 6. isPropertyOf : 특정 객체의 프로토타입 체인에 현재 객체가 존재하는지 검사
var day = new Date(); // Date 객체를 생성함
// 객체 day의 프로토타입이 Date.prototype 인지를 검사함.
Date.prototype.isPrototypeOf(day); // true
Date.prototype.isPrototypeOf(new String()); // false

// 7. isExtensible: 객체에 새로운 프로퍼티를 추가할수 있는지 여부
// preventExtensions : 새로운 프로퍼티를 추가할 수 없도록 처리함
// 객체 day에 새로운 프로퍼티를 추가할 수 있는지 검사함.
Object.isExtensible(day); // true
// 해당 객체에 새로운 프로퍼티를 추가할 수 없도록 설정함.
var myDay = Object.preventExtensions(day);
Object.isExtensible(day); // false

// 8. isSealed : 프로퍼티를 삭제 할 수 있는 지 여부
// seal : 프로퍼티를 삭제할 수 없도록 처리함
var person = {
		name: '홍길동',
		region: '서울특별시',
		hobby: '기타'
}
Object.seal(person);
delete person.name;

// 9. keys : 자신의 속성(key값)을 배열로 리턴(열거가능만)
// getOwnPropertyNames : 모든 속성을 배열로 리턴
var object = {name:'윤인성'};
Object.defineProperty(object, 'region', {
	value:'서울특별시'
});
console.log(Object.keys(object));
console.log(Object.getOwnPropertyNames(object));

/*array 객체 - 정렬*/
function Student(name, korean, math, english, science){
	//속성
	this.이름 = name;
	this.국어 = korean;
	this.수학 = math;
	this.영어 = english;
	this.과학 = science;
	// 메소드
	this.getSum = function(){
		return this.국어 + this.수학 + this.영어 + this.과학;
	};
	this.getAverage = function(){
		return this.getSum() / 4;
	};
	this.toString = function(){
		return this.이름 + '\t' + this.getSum() + '\t' + this.getAverage();
	};
}
//학생 정보 배열을 만듬
var students = [];
students.push(new Student('굴리트', 90, 91, 92, 93));
students.push(new Student('오언', 80, 91, 92, 97));
students.push(new Student('말디니', 90, 71, 92, 83));
students.push(new Student('바란', 90, 91, 62, 73));
students.push(new Student('호돈', 40, 51, 92, 43));
//정렬하고 1등부터 3등까지만 배열에 남겨둡니다.
students.sort(function (left,right){
	return right.getSum() - left.getSum();
});
students = students.slice(0,3);
// 출력
var output = '이름\t총점\t평균\n';
for(var i in students){
	output += students[i].toString() + '\n';
}
console.log(output);
/*
이름	총점	평균
굴리트	366	91.5
오언	360	90
말디니	336	84*/






/*String 예제*/
// 자바스크립트에서의 string은 원소스를 바꿀수 없음.
var str = "Please locate where 'locate' occurs!";
console.log(str.indexOf("locate")); // 7
console.log(str.indexOf("locate", 15)); // 21 시작 index 존재
console.log(str.lastIndexOf("locate")); // 21
console.log(str.slice(7, 13)); // locate
console.log(str.slice(7)); // index 7 이후의 string
console.log(str.substring(7, 13)); // locate
console.log(str.replace("Please", "Never")); // Never ~
console.log(str.toUpperCase()); // 대문자로
console.log(str.concat("", "Wow")); //  Please locate where 'locate' occurs!Wow
console.log(str.charAt(0)); // P
console.log(str.charCodeAt(0)); // 80 (UTF-16 리턴) 
console.log(str[0]); // P. 값은 변경안됨
console.log(str.split("'")); // (3) ["Please locate where ", "locate", " occurs!"] arr로 리턴 
console.log(str.split(""));
// (36) ["P", "l", "e", "a", "s", "e", " ", "l", "o", "c", "a", "t", "e", " ", "w", "h", "e", "r", "e", " ", "'", "l", "o", "c", "a", "t", "e", "'", " ", "o", "c", "c", "u", "r", "s", "!"]
// 구분자 없을경우는 -> 문자열을 하나씩 arr로

/*Date 예제*/
var d = new Date();
console.log(d.getFullYear()); // set으로도 쓸수 있다.
console.log(d.getMonth()+1); // +1해야 정상 월 나옴
console.log(d.getDate()); // 일
console.log(d.getHours()); // 시
console.log(d.getMinutes()); // 분
console.log(d.getSeconds()); // 초
console.log(d.getMilliseconds()); // 밀리초
console.log(d.getDay()); // 0 ~ 6 (일 ~ 토)

var d = new Date("2015-03-25");
var d = new Date("2015-03");
//YYYY-MM-DDTHH:MM:SSZ
var d = new Date("2015-03-25T12:00:00Z");

//Date 객체
// year, month, day, hours, minutes, seconds, milliseconds
// toXXXString()
var output = '';
var date = new Date();
output += '★toDateString: ' + date.toDateString() + '\n';
output += '★toGMTString: ' + date.toGMTString() + '\n';
output += '★toLocaleDateString: ' + date.toLocaleDateString() + '\n';
output += '★toLocaleString: ' + date.toLocaleString() + '\n';
output += '★toLocaleTimeString: ' + date.toLocaleTimeString() + '\n';
output += '★toString: ' + date.toString() + '\n';
output += '★toTimeString: ' + date.toTimeString() + '\n';
output += '★toUTCString: ' + date.toUTCString() + '\n';
alert(output);

//날짜간격 구하기
var before = new Date('March 1, 1991');
var interval = date.getTime() - before.getTime();
interval = Math.floor(interval / (1000*60*60*24));
console.log('interval : ' + interval + '일'); // 10419일

// 프로토 타입에 날짜 간격 구하는 메소드 추가
Date.prototype.getInterval = function(otherDate){
	var interval;
	if(this > otherDate){
		interval = this.getTime() - otherDate.getTime();
	} else {
		interval = otherDate.getTime() - this.getTime();
	}
	return Math.floor(interval / (1000*60*60*24));
};
console.log('interval2 : ' + date.getInterval(before) + '일'); // 10419일

/*Math객체*/
console.log(Math.round()); // 0 ~ 1
// min ~ max 사이 random value, min/max 모두 포함
function getRndInteger(min, max){
	return Math.floor(Math.random()* (max - min + 1)) + min;
}

/*브라우저 객체 모델*/
// history 예제 - 보안 문제 존재.
function history_back(){
	history.back();
}

function history_forward(){
	history.forward();
}

function history_go(){
	var page = document.frm.txtGo.value; // 폼이름으로 바로 접근 가능
	history.go(page);
}

/*문서 객체 모델 - DOM*/
// getElementById : ID를 통해 특정 요소노드의 Object를 리턴한다.
// getElementByTagName : 특정태그를 사용하는 요소노드들을 배열로 리턴한다.
var items = document.getElementByTagName("li"); // <li>태그에 대한 목록리스트
for(var i=0 ; i<items.length; i++){
	alert(typeof items[i]);
}
//문서 내에 모든 요소노드의 개수를 알고싶으면
document.getElementByTagName("*").length;
// 특정 요소노드 하위로 얼마나 많은 요소노드가 있는지 확인
var shopping = document.getElementById("purchase");
var items = shopping.getElementByTagName("*");

// 속성다루기
// getAttribute : 요소노드에 접근한 뒤 각 속성값들을 얻기 위해 사용
var paras = document.getElementByTagNames("p");
for(var i = 0; i < paras.length; i++){
	var title_text = paras[i].getAttribute("title");
	if(title_text) // if(title_tex!=null) 과 같은 의미
		alert(title_text);
}
// setAttribute : p태그의 title속성을 변경하고자 한다면
var shopping = document.getElementById("purchase");
shopping.setAttribute('title', 'a list of goods');
// childNodes : 요소노드의 속성으로서 모든 자식을 포함하는 배열을 리턴한다.
// 요소노드, 텍스트노드를 child배열에 포함하여 반환
// getElementByTagName은 결과를 배열로 리턴한다. body는 문서에서 하나만 존재하므로 0번째 값을 리턴하면 된다.
// body의 childNode들을 조사해 보면 body 바로 밑에 연결되어 있는 node들만 가져온다.
var body_element = document.getElementByTagName("body")[0];
var child_elements = body_element.childNodes;

for(var i = 0; i < child_elements.length; i++){
	alert(child_elements[i].nodeName); // nodeName : node의 tag명
}

</script>
</head>
<body>

	<input type="button" value="Stack 객체를 만들기" onClick="question1()" />
	<input type="button" value="Queue 객체를 만들기" onClick="question2()" />
	<input type="button" value="Set 객체를 만들기" onClick="question3()" />
	
	<br><br>
	<form name="frm">
	<input type="button" value="back" onClick="history_back()" />
	<input type="button" value="forward" onClick="history_forward()" />
	<br>history에 저장된 페이지수 : <script>document.write(history.length);</script>
	<br>이동하고 싶은 전 페이지수 : <input type="text" name="txtGo" value='-2' size='4'>
	<input type="button" value="go" onClick="history_go()" />
	</form>
    
    
	
</body>
</html>

 

// Date 객체 예제 결과

And