쌍용교육센터 - 36일

개발자가 되고 싶어요 ㅣ 2024. 4. 8. 20:40

2024.04.08

 

instanceof

<script>
	function Student(name){
		this.name = name;
	}
	
	//객체 생성
	let student = new Student('홍길동');
	
	//해당 객체가 어떤 함수를 통해 생성됐는지 확인할 때 instanceof 키워드를 사용.
	//객체가 속한 클래스와 상위 클래스 체크
	document.write(student instanceof Student);
	document.write('<br>');
	document.write(student instanceof Object);
	document.write('<br>');
	document.write(student instanceof Number);
	document.write('<br>');
</script>

 

Client Object

<script>
	/* 
	클라이언트 오브젝트(브라우저 관련 객체)
	window
	  |
	location history frame document screen navigator
				                     |	
	anchor applet area form image layer link plugin title
						           |
	button checkbox fileupload hidden select password radio reset submit text textarea
										                   |
									                   option
									   
	window 메서드
	window.alert() : 경고창
	window.prompt() : 입력창
	window.confirm() : 선택창
	*/
	window.alert('경고창'); // = alert('경고창');
	let season = window.prompt('좋아하는 계절은?','');// = prompt('좋아하는 계절은?','');
	document.write('좋아하는 계절은 '+season+'이다<br>');
	
	let choice = window.confirm('야근을 하겠습니까?'); // = confirm('야근을 하겠습니까?');
	// 확인->true, 취소->false 반환
	if(choice) {
		document.write('야근 확정!');
	} else {
		document.write('야근 취소!');
	}
</script>

 

window 새 창 열고 닫기


/* 
window.open(url,새창 이름,옵션) : 창 열기
옵션
width : 새 윈도우의 넓이
height : 새 윈도우의 높이
location : 주소 입력창 유무
menubar : 메뉴의 유무
resizable : 화면 크기 조절 가능 여부
status : 상태 표시줄의 유무
toolbar : 툴바 유무
scrollbars : 스크롤바 유무
left : 창의 가로축 위치 지정
top : 창의 세로축 위치 지정

window.close : 창 닫기
*/
let win;
function winOpen(){
	//새 창 열기
	win = window.open('<<a href=https://www.naver.com>https://www.naver.com</a>>','child','toolbar=no,location=no',
			'status=no,menubar=no,resizable=no,scrollbars=no,width=400,height=300');
}
function winClose(){
	//새로 열린 창 닫기
	win.close();
}
 

 

일정 시간 후 한번 함수 실행 or 마다 반복 함수 실행

<script>
		/* 
		setTimeout(function,millisecond) : 일정 시간 후에 함수를 한 번 실행
		setInterval(function,millisecond) : 일정 시간마다 함수를 반복해서 실행
		*/
		
		//윈도우가 로드될 때
		window.onload = function(){
			alert('경고창을 닫고 3초 후 이 페이지는 종료됩니다.');
			//3초 후에 함수를 실행
			window.setTimeout(function(){
				window.close(); //현재 창을 닫음
			},3000);
		};
	</script>

 

location

<script>
		document.write('location,href : ' + location.href + '<br>');
		document.write('location.protocol : ' + location.protocol + '<br>');
		document.write('location.host : ' + location.host + '<br>');
		document.write('location.hostname : ' + location.hostname + '<br>');
		document.write('location.port : ' + location.port + '<br>');
		document.write('location.pathname : ' + location.pathname);
		
		<input type="button" value="이동(href)" onclick="location.href='s01_window.html'">
	
		<input type="button" value="이동(assign)" onclick="location.assign('s02_window.html')">
	
		<!-- 이동하면서 히스토리를 지우기 때문에 뒤로가기가 안됨 -->
		<input type="button" value="이동(replace)" onclick="location.replace('s02_window.html')">
	
		<!-- 새로고침 -->
		<input type="button" value="새로고침" onclick="location.reload()">
		
		
	</script>

 

history

<body>
	<input type="button" value="이전" onclick='history.back()'>
	<input type="button" value="이전(go(-1))" onclick='history.go(-1)'>
	<input type="button" value="다음(forward)" onclick='history.forward()'>
	<input type="button" value="다음(go(1))" onclick='history.go(1)'>
</body>

 

Array

<script>
	//배열 생성
	const array1 = new Array();//빈 배열
	//배열 요소의 목록
	document.write(array1 + '<br>');
	//배열 길이
	document.write(array1.length + '<br>');
	
	//배열 생성
	const array2 = new Array(10);//배열의 길이를 10으로 지정
	//배열 요소의 목록
	document.write(array2 + '<br>');
	//배열의 길이
	document.write(array2.length + '<br>');
	
	//배열 생성(초기값 지정)
	const array3 = new Array(52,273,103,57,32);
	//배열 요소의 목록
	document.write(array3 + '<br>');
	//배열의 길이
	document.write(array3.length);
	</script>

 

String

<script>
		let msg = '세상의 끝에서 세상을 노래하다';
				 //012 345678910	length=16
		
		document.write(msg.length + '<br>');//문자열의 길이
		document.write(msg.charAt(8) + '<br>');//해당 인덱스의 문자 반환
		document.write(msg.indexOf('상') + '<br>');//해당 문자의 인덱스 반환
		document.write(msg.indexOf('노래' + '<br>'));//해당 문자의 첫 인덱스만 반환
		document.write(msg.lastIndexOf('상'));
		document.write('------------------------<br>');
		
		//문자열에서 부분 문자열 추출
		//지정한 인덱스부터 끝인덱스까지 추출
		document.write(msg.substring(5) + '<br>');
		document.write(msg.substr(5) + '<br>');
		document.write(msg.slice(5));
		document.write('------------------------<br>');
		
		//시작 인덱스부터 끝 인덱스전까지
		document.write(msg.substring(1,5) + '<br>'); //상의 끝
		//시작 인덱스, 추출할 문자 개수
		document.write(msg.substr(5,2) + '<br>');//에서
		//시작 인덱스부터 끝 인덱스전까지
		document.write(msg.slice(1,5) + '<br>');//상의 끝
		
		
		let msg2 = 'Hello WORLD';
		
		document.write(msg.toUpperCase() + '<br>');
		document.write(msg.toLowerCase() + '<br>');
		
		let msg3 = '하하';
		
		document.write(msg.concat(msg3));
		document.write('------------------------<br>');
		
		let msg4 = '2024-04-08';
		let array = msg4.split('-');
		//배열 요소의 목록
		document.write(array);
		
	</script>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
function check(){
	//입력한 이메일 값 읽기
	let email = document.form1.email.value;
	let n = email.indexOf('@');
	alert(n);
	if(n>0){							//시작 인덱스, 추출할 문자의 개수
		document.form1.id.value = email.substr(0,n);
	} else {
		document.form1.email.value = '';//값 초기화
		alert('이메일 형식에 맞게 입력하세요.');
	}
	
}
</script>
</head>

<body>
	<form name="form1">
		id : <input type="text" name="id" placeholder="아이디는 이메일에서 추출" readonly="readonly">
		Email : <input type="text" name="email"><br>
		<input type="button" value="입력" onclick="check()">
	</form>
</body>

 

Date

<script>
	const now = new Date();
	document.write('now의 값 : ' + now + "<br>");
	document.write("now.toString() : " + now.toString());
	
	document.write('오늘 : ' + now.toLocaleString());
	document.write('오늘의 날짜 : ' + now.toLocalDateString +'<br>');
	document.write('오늘의 시간 : ' + now.toLocalTimeString +'<br>');
	
	document.write('연도 : ' + now.getFullYear()+'<br>');
	
	document.write('월 : ' + (now.getMonth+1)+'<br>');
	document.write('일 : ' + now.getDate('<br'));
	//요일:0(일)~6(토)
	document.write('요일 : ' + now.getDay()+'<br>');
	//시 : 0~23
	document.write("시 : " + now.getHours()+'<br>');
	document.write("분 : " + now.getMinutes()+'<br>');
	document.write("초 : " + now.getseconds()+'<br>');
	document.write("밀리초 : " + now.getMilliseconds()+'<br>');
	</script>

 

tagName

<script>
	//윈도우가 로드될 때 onload에 대입된 함수가 실행
	window.onload=function(){
		//태그명을 통해서 태그를 탐색해서 문서 객체로 반환
		//복수의 태그가 존재할 수 있기 때문에 배열로 반환
		const header1 = document.getElementsByTagName('태그명');
		header1[0].innerHTML = '달빛이 찬란한 호수';
		header1[1].innerHTML = '흰 눈이 눈 부신 들판';
		
		//반복문 사용하기
		const header3 = document.getElementsByTagName('태그명');
		
		for(let i=0; i<header3.length; i++){
			if(i%2==1){
				header3[i].innerHTML = '우주';
			} else {
				header3[i].innerHTML = '지구';
			}
		}
	}
</script>

 

id를 이용한 문서 객체 탐색

<script>
//윈도우가 로드될 때 onload에 대입된 function를 실행
window.onload=function(){
	const header1 = document.getElementById('아이디명');
	const header2 = document.getElementById('아이디명');
	
	//태그의 내용 변경
	header1.innerHTML = '하하';
	header2.innerHTML = '호호';
}

</script>

 

태그명과 id를 사용해서 문서 객체 탐색

<script>
//윈도우가 로그될 때 onload에 대입된 함수가 실행
	window.onload = function(){
		const allSpans = document.getElementsByTagName('span');
		
		let output = '[모든 span 태그의 text 출력]\\n'; //경고창에 <br>붙이면 다 보임
		for(let i=0; i<allSpans.length; i++){
			output += allSpans[i].innerHTML + '\\n';
		}
		alert(output);
		
		//id가 foo인 p 태그 반환
		const foo = document.getElementById('foo');
		//id가 foo인 p 태그의 자식 태그 중 span 태그 반환
		const fooSpans = foo.getElementsByTagName('span');
		
		let output2 = '[id가 foo인 p태그 하위 태그 중 모든 span 태그의 text 출력]\\n';
		for(let i=0;i<fooSpans.length;i++){
			output2 += fooSpans[i].innerHTML + '\\n';
		}
		alert(output2);
		
	};
</script>

 

태그명을 통해 태그 객체들의 정보 처리

<script>
window.onload=function(){
	//태그명을 통해서 태그 객체들을 배열에 담아 반환
	const prev = document.getElementsByName('prev');
	prev[0].innerHTML = '이전';
	
	const next = document.getElementsByName('next');
	next[0].innerHTML = '다음';
	
	const country = document.getElementsByName('country');
	country[0].checked=true;
	
	const comment = document.getElementsByName('comment');
	comment[0].value = '간단한 설명 입력';
}

</script>

'IT 국비 교육' 카테고리의 다른 글

쌍용교육센터 - 38일  (0) 2024.04.11
쌍용교육센터 - 37일  (0) 2024.04.09
쌍용교육센터 - 35일  (0) 2024.04.05
쌍용교육센터 - 34일  (0) 2024.04.04
쌍용교육센터 - 33일  (1) 2024.04.03