210916 수
9. 숫자 & 문자 & 날짜
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>09_숫자 문자 날짜 다루기</title>
</head>
<body>
<h1>숫자 문자 날짜 다루기</h1>
<h3>1. 숫자형 메소드</h3>
<p>
isNaN(value) - 인수를 숫자로 변환한 다음 NaN(Not a Number : 에러를 나타내는 값)인지 테스트
(*추가 : 문자이면 true, 숫자이면 false)
<br>
isfinite(value) - 인수를 숫자로 변환하고 변환한 숫자가 NaN/Infinity/-Infinity가 아닌
일반 숫자인 경우 true를 반환함
(*추가 : 숫자이면 true, 문자나 NaN/Infinity/-Infinity이면 false)
</p>
<script>
function test1(){
console.log("isNaN(NaN) : " + isNaN(NaN));
// 의미 : NaN이 숫자가 아닙니까? yes
// 답 : true
console.log("isNaN('abc') : " + isNaN('abc'));
// 의미 : abc가 숫자가 아닙니까? yes
// 답 : true
console.log("isNaN('1') : " + isNaN('1'));
// 답 : false
console.log("isNaN(2.8) : " + isNaN(2.8));
// 답 : false
// 타입은 스트링이지만 숫자로 변환돼서 false
console.log("NaN == NaN : " + NaN == NaN);
// false
// *NaN은 NaN 자기 자신을 포함하여 그 어떤 값과도 같지 않음
// => isNaN 메소드 기능 필요
console.log("isFinite('1') : " + isFinite('1'));
// true
// 의미 : 숫자인가요? 네
console.log("isFinite('abc') : " + isFinite('abc'));
// false
// 의미 : 숫자인가요? 아니요
console.log("isFinite(1/0) : " + isFinite(1/0));
// false
// 의미 : 숫자인가요? 아니요(무한대)
console.log("isFinite(Infinity) : " + isFinite(Infinity));
// false
// 의미 : 숫자인가요? 아니요(무한대)
console.log("isFinite(-Infinity) : " + isFinite(-Infinity));
// false
// 의미 : 숫자인가요? 아니요(무한대)
// 자바스크립트의 NaN 값은 not a number라는 뜻으로 즉 숫자가 아니라는 의미이다.
// typeof로는 NaN와 숫자를 구분할 수 없거니와 자신과의 비교도 불허한다
}
// test1();
</script>
<p>
Number는 문자열 앞 뒤 공백을 제외하고 다른 문자가 섞여 있으면 형변환이 불가능함<br>
하지만 parseInt/parseFloat를 사용하면 문자열에서 숫자만 읽고,
읽은 숫자를 에러가 발생하기 전에 반환해주는 형변환을 사용할 수 있음<br>
ex."300px", "16pt" 등
</p>
<script>
function test2(){
let intNum = "3";
let floatNum = "1.234";
let stringNum = "300px";
console.log("Number(intNum) : " + Number(intNum));
console.log("parseInt(intNum) : " + parseInt(intNum));
console.log("parseFloat(intNum) : " + parseFloat(intNum));
// 세 값 모두 : 3
console.log("Number(intNum) : " + Number(floatNum));
// 답 : 1.234
console.log("parseInt(intNum) : " + parseInt(floatNum));
// 답 : 1
// => 무조건 정수로 변환해 줌
console.log("parseFloat(intNum) : " + parseFloat(floatNum));
// 답 : 1.234
console.log("Number(intNum) : " + Number(stringNum));
// NaN
console.log("parseInt(intNum) : " + parseInt(stringNum));
// 300 => 그 이전까지의 값만 불러온 것
console.log("parseFloat(intNum) : " + parseFloat(stringNum));
// 300
}
// test2();
</script>
<h3>2. 문자형 메소드</h3>
<p>
문자형의 경우 작은 따옴표와 큰 따옴표 모두 사용 가능하며
또 한 가지는 backtick(`)을 사용할 수 있음<br>
백틱은 문자열 여러 줄에 걸쳐서 쓸 수 있게 해주고 문자열 중간에 ${...}을 사용해
표현식도 넣을 수 있음<br>
문자열 내의 글자 하나를 얻으려면 문자열[위치 인덱스]를 사용함<br>
slice, substr, substring : 부분 문자열 얻기<br>
indexOf : 부분 문자열의 위치를 얻기<br>
includes/startsWith/endsWith : 부분 문자열 여부 알기<br>
trim : 문자열 앞 뒤 공백 제거<br>
toLowerCase, toUppercase : 소문자, 대문자로 변경
</p>
<script>
function test3(){
let str = `My
Name
is
Jennie.`;
console.log("`${str}` : " + `${str}`);
// `${str}` : My
// Name
// is
// Jennie.
console.log("str : " + str);
// str : My
// Name
// is
// Jennie.
let num = '0123456789';
console.log('num : ' + num);
// num : 0123456789
// 방법1) 문자열 내 글자 하나 추출 : 문자열[위치인덱스]
console.log('num[0] : ' + num[0]);
// num[0] : 0
console.log('num[1] : ' + num[1]);
// num[1] : 1
// 방법2) for of문 사용
for(let char of num){
console.log(char);
// 답 : 0~9까지 각각 행으로 출력됨
}
// 부분 문자열 얻기
// substr(start, length)
console.log("num.substr(5,5) : " + num.substr(5,5));
// 답 num.substr(5,5) : 56789
// 5라는 위치에서 다섯개
// substring(start, end)
console.log("num.substring(3, 8) : " + num.substring(3, 8));
// 답 num.substring(3, 8) : 34567
// 3부터 7까지(8전)
// slice(start, end)
console.log("num.slice(3, 7) : " + num.slice(3,7));
// 답 num.slice(3, 7) : 3456
// 부분 문자열의 위치/여부 알기
// indexOf : 인덱스 위치 반환, 없으면 -1반환.
console.log("num.indexOf('9') : " + num.indexOf('9'));
// 답 num.indexOf('9') : 9
console.log("num.indexOf('a') : " + num.indexOf('a'));
// 답 num.indexOf('a') : -1
// 값이 없어서 -1 반환
//includes : 포함 여부 반환, true or false
console.log("num.includes('9') : " + num.includes('9'));
// 답 num.includes('9') : true => 포함된다
console.log("num.includes('a') : " + num.includes('a'));
// 답 num.includes('a') : false => 미포함된다
// startsWith/endsWith : 해당 문자열로 시작하는지/끝나는지, true or false
console.log("num.startsWith('012') : " + num.startsWith('012'));
// 답 true
console.log("num.startsWith('abc') : " + num.startsWith('abc'));
// 답 false
console.log("num.endsWith('789') : " + num.endsWith('789'));
// 답 true
console.log("num.endsWith('xyz') : " + num.endsWith('xyz'));
// 답 false
}
test3();
</script>
<h3>3. Date 객체</h3>
<p>
날짜와 시간을 나타내는 객체로 월은 0부터 시작하며
요일은 0:일요일 ~ 6:토요일을 나타낸다<br>
날짜끼리의 연산도 가능한데 이는 Date가 숫자형으로 바뀔 때 타임스탬프가 반환되어서이다<br>
(타임스탬프 : 1970년도의 첫 날을 기준으로 흘러간 밀리초를 나타내는 정수)
</p>
<script>
function test4(){
// new Date() : 현재 날짜 반환
let now = new Date();
console.log(now);
// 답 : Wed Sep 15 2021 16:58:32 GMT+0900 (한국 표준시)
// new Date(milliseconds)
// 1970년 1월 1일 0시 0분 0초 기준
let start = new Date(10000);
// 위의 현재 날짜 반환에 0을 넣어준 것
console.log(start);
// 답 Thu Jan 01 1970 09:01:40 GMT+0900 (한국 표준시)
// 밀리세컨 기준이므로 일 * 시 * 분 * 초 * 밀리초 => 1년 뒤
let when = new Date(365 * 24 * 60 * 60 * 1000);
console.log(when);
// 답 Fri Jan 01 1971 09:00:00 GMT+0900 (한국 표준시)
// new Date(datestring)
let startDate = new Date("2021-06-18");
console.log(startDate);
// 답 Fri Jun 18 2021 09:00:00 GMT+0900 (한국 표준시)
// new Date(year, month, date, hours, minutes, seconds, ms)
let day1 = new Date(2021, 6-1, 18);
let day2 = new Date(2021, 6-1, 18, 15, 30, 15, 500);
// => 월은 0부터 시작이므로 6-1을 해줘야 6월이다
console.log(day1);
// 답 Fri Jun 18 2021 00:00:00 GMT+0900 (한국 표준시)
console.log(day2);
// 답 Fri Jun 18 2021 15:30:15 GMT+0900 (한국 표준시)
// 현재 날짜 년월일시분초 얻기
console.log("getFullYear() : " + now.getFullYear());
// getFullYear() : 2021
console.log("getMonth()+1 : " + (now.getMonth() + 1));
// getMonth()+1 : 9
console.log("getDate() : " + now.getDate());
// getDate() : 15
console.log("getDay() : " + now.getDay());
// getDay() : 3
console.log("getHours() : " + now.getHours());
// getHours() : 17
console.log("getMinutes() : " + now.getMinutes());
// getMinutes() : 10
console.log("getSeconds() : " + now.getSeconds());
// getSeconds() : 34
console.log("getMilliseconds() : " + now.getMilliseconds());
// getMilliseconds() : 498
// 내가 원하는 년월일시분초 설정하기
let endDate = new Date();
endDate.setFullYear(2022);
endDate.setMonth(1-1);
endDate.setDate(24);
endDate.setHours(21);
endDate.setMinutes(50);
endDate.setSeconds(0);
endDate.setMilliseconds(0);
console.log(endDate);
// Mon Jan 24 2022 21:50:00 GMT+0900 (한국 표준시)
// 날짜 간의 차이 타임스탬프로 계산
console.log(endDate - startDate);
// 19054200000 => 밀리세컨 단위
console.log((endDate - now) / (24 * 60 * 60 * 1000));
// 131.1894728587963 => 일 단위
}
test4();
</script>
</body>
</html>
10. DOM
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>10_DOM</title>
</head><body><h1>DOM(Document Object Model)</h1>
<p>
HTML에 있는 태그를 객체화하여 자바스크립트에서 다룰 수 있게 한 것<br>
모든 노드 객체에 접근할 수 있는 요소와 메소드 제공<br>
HTML에 있는 태그를 구조화(트리) 하였을 때 각각의 태그가 노드<br>
- 요소 노드(Elements Node) : 태그 그 자체 의미<br>
- 텍스트 노드(Text Node) : 태그에 기록되어 있는 문자<br>
* 텍스트 노드를 가지는 태그(h?, p 등)와 가지지 않는 태그(img 등)가 있음
</p>
<h1>DOM 탐색하기</h1>
<h3>1. documentElement, head, body</h3>
<script>
function test1() {
console.log("----- HTML ------")
console.log(document.documentElement);
// 전체 출력됨
console.log("----- HEAD ------");
console.log(document.head);
// 헤드 부분 출력됨
console.log("----- BODY ------ ");
console.log(document.body);
// 바디 부분 출력됨
}
// test1();
</script>
<h3>2. 자식 노드 탐색 : childNodes, firstChild, lastChild</h3>
<p>
자식 노드(child node, children)는 바로 아래의 자식 요소를 나타냄<br>
후손 노드(descendants)는 중첩 관계에 있는 모든 요소를 나타냄
</p>
<ul>
<li><a href="#">링크1</a></li>
<li><a href="#">링크2</a></li>
<li><a href="#">링크3</a></li>
</ul>
<script>
function test2() {
console.log("----- body의 자식 노드들(childNides)-----")
console.log(document.body.childNodes);
// 답
// NodeList(18) [text, h1, text, p, text,
// h1, text, h3, text, script, text,
// h3, text, p, text, ul, text, script]
// 자식 노드들이 배열처럼 출력됨
console.log("------------------------------------------");
for (let i = 0; i < document.body.childNodes.length; i++) {
console.log(document.body.childNodes[i]);
}
// 자식 노드들이 한 행 한 행 출력됨
// 개행이 있으면 text로 출력됨
console.log("------------------------------------------")
// ul 태그의 인덱스 찾아서 자식 출력해보기
console.log(document.body.childNodes[14].childNodes);
// 답 NodeList(7) [text, li, text, li, text, li, text]
console.log(document.body.childNodes[14].firstChild);
console.log(document.body.childNodes[14].lastChild);
// 여기 답 뭐지?
}
// test2();
</script>
<h3>3. DOM 컬렉션</h3>
<p>
NodeList는 마치 배열같아 보이지만 배열이 아닌 반복 가능한 유사 배열 객체인 컬렉션<br>
for of 반복문은 사용 가능하지만 배열 메소드는 쓸 수 없음<br>
DOM 컬렉션은 읽는 것만 가능하며 childNodes[i] = 값; 을 이용해서 자식 노드를 교체하는 것이
불가능함<br>
자식 노드 변경을 위해서는 별도의 메소드가 필요함
</p>
<h3>4. 형제 노드 탐색 : nextSibling, previousSibling</h3>
<p>
previousSibling : 이전 형제 노드에 대한 정보<br>
nextSibling : 다음 형제 노드에 대한 정보
</p>
<h3>5. 부모 노드 탐색 : parentNode</h3>
<script>
function test3() {
// 바디와 헤드는 html의 자식
// head / body 태그의 부모는 html
// console.log(document.head.parentNode);
// console.log(document.body.parentNode);
// 답 : 둘다 똑같이 html 전체 파일 출력됨
//head / body 개행 없을 시 서로가 형제
console.log(document.head.nextSibling);
// 답 : body 출력됨
console.log(document.body.previousSibling);
// 답 : head 출력됨
// *head, body 개행 붙여주세요
}
// test3();
</script>
<h1>요소 간 이동</h1>
<h3>1. 부모 요소 : parentElement<br>
2. 자식 요소 : children, firstElementChild, lastElementChild<br>
3. 형제 요소 : nextElementSibling, previosElementSibling
</h3>
<p>
탐색 관련 프로퍼티는 모든 종류의 노드(텍스트, 요소, 주석)를 참조하지만
대부분은 요소 노드를 조작하는 작업이므로 요소 노드만 탐색하는 속성이 필요함
</p>
<script>
function test4() {
for (let elem of document.body.children) {
console.log(elem);
// 바디의 요소들만 출력됨
}
console.log("------------------------------------------");
console.log(document.body.children[7].firstElementChild);
// <li>..</li>
console.log(document.body.children[7].lastElementChild);
// <li>..</li>
console.log(document.body.children[7].nextElementSibling);
// 스크립트 출력됨
console.log(document.body.children[7].previousElementSibling);
// <p>..</p>
console.log(document.body.children[7].parentElement);
// <body>..</body>
}
// test4();
</script>
</body>
</html>
11. 요소 검색
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>11_요소 검색</title>
<style>
.area {
width: 500px;
height: 200px;
border: 1px solid black;
}
</style>
</head>
<body>
<h1>원하는 요소 노드에 접근하기</h1>
<h3>1. document.getElementById</h3>
<p>
요소에 id 속성이 있으면 위치에 상관 없이
(부모, 자식, 형제 등의 상대적 위치와 관계없이)
document.getElementById(id) 메소드를 통해 접근할 수 있음<br>
*id 속성 값을 그대로 딴 전역 변수를 이용한 접근도 가능하지만
해당 id와 동일한 변수가 생기는 이름 충돌 가능성이 있어서
지양하는 것이 좋음*<br>
문서 내의 id 속성 값은 중복되어서는 안되면
중복 된다면 document.getElementById 메소드의 동작에 문제가 발생함
</p>
<div id="area1" class="area">div 영역
<p id="area2">p 태그 영역</p>
</div>
<div id="area1" class="area">div 영역</div>
<script>
//요소 접근
let elem = document.getElementById('area1');
// 동일 아이디라면 첫번째 문서에서 불러온 값을 적용시킨다
// 색상 변경
elem.style.background = 'skyblue';
// let area2 = 10;
area2.style.background = 'blue';
// 11_요소 검색.html:41 Uncaught TypeError
// : Cannot set properties of undefined (setting 'background')
// area2를 직접 사용하면 변수가 이름이 같을 때 오류 생김
</script>
<div id="area3" class="area"></div>
<button onclick="accessId();">클릭마다 색 변경</button>
<script>
function accessId() {
let area3 = document.getElementById('area3');
let bgColor = area3.style.backgroundColor;
console.log(bgColor);
if (bgColor == 'red') {
area3.style.backgroundColor = 'yellow';
} else {
area3.style.backgroundColor = 'red';
}
}
</script>
<h3>2. querySelector</h3>
<p>
document.querySelector('선택자') : 제공한 선택자와 일치하는 문서 내 첫 번째 Element를 반환함<br>
document.querySelectorAll('선택자') : 제공한 선택자와 일치하는 문서 내 모든 Element를 반환함
</p>
<div class="test">
<h1>first</h1>
</div>
<div class="test">
<h1>second</h1>
</div>
<script>
let myDiv = document.querySelector('.test');
// 답
// <div class="test" style="color: red;">
// <h1>first</h1>
// </div>
console.log("===========")
console.log(myDiv);
let myDivs = document.querySelectorAll('.test');
console.log("===========")
console.log(myDivs);
// 답 NodeList(2) [div.test, div.test]
console.log("===========")
myDivs[0].style.color = 'red';
myDivs[1].style.color = 'green';
</script>
<p>
element.querySelector('선택자') : 제공한 선택자와 일치하는 element내 첫번째 요소 반환<br>
element.querySelectorAll('선택자') : 제공한 선택자와 일치하는 element내 모든 요소 반환
</p>
<div class="first">
<div class="second">
<ul>
<li>test1</li>
<li>test2</li>
<li>test3</li>
<li>test4</li>
</ul>
</div>
</div>
<script>
let first = document.querySelector('.first');
let myLi = first.querySelector('.second li:nth-child(3)');
// 의미 : second의 세 번째 자식이라는 뜻
let myLis = first.querySelectorAll("li");
console.log(first);
// 답 : <div class = "first">..</div>
console.log(myLi);
// 답 : <li>.."test3"..</li>
console.log(myLis);
// 답 : NodeList(4) [li, li, li, li]
myLi.style.color = 'red';
// 답 : <li></li>의 세 세번째 목록 색이 바뀜
myLis[0].style.backgroundColor = 'gray';
// 답 : <li></li>의 첫 번째 목록의 색이 바뀜
</script>
<h3>3. closest</h3>
<p>
element.closest('선택자') : element 자기 자신을 포함하여
제공한 선택자와 일치하는 가장 가까운 조상 요소를 반환함
</p>
<div class="area">
<ul class="korean-food">
<li class="menu">불고기백반</li>
<li class="menu">된장찌개</li>
<li class="menu">김치찌개</li>
</ul>
</div>
<script>
let menu = document.querySelector('.menu');
console.log(menu);
// 의미 : 전체 문서 중 menu 클래스에 있는 요소 중 가장 첫 번째 요소를 찾아라!
// 답 : 불고기백반이 있는 곳 리스트
console.log(menu.closest('.korean-food'));
// 답 : <ul class="korean-food">..</ul>
console.log(menu.closest('.area'));
// 답 : <div>와 <ul>까지만 출력됨
console.log(menu.closest('h3'));
// 답 : h3은 li의 조상이 아니므로 null
</script>
<h3>4. matches</h3>
<p>
element.matches('선택자') : element가 선택자와 일치하는지 여부 반환<br>
요소가 담겨있는 배열 등을 순회해서 원하는 요소만 걸러내고자 할 때 사용
</p>
<script>
console.log("xxxxxxxxxxxxxxxxxxxx");
for (let elem of document.body.children) {
if (elem.matches('.area')) {
console.log(elem);
}
}
// 답 : 클래스로 area가 있는 모든 요소들이 다 반환됨
console.log("xxxxxxxxxxxxxxxxxxxx");
</script>
<h3>5.
getElementsByTagName(tag),
getElementsByClassName(className),
getElementsByName(name)
</h3>
<p>
태그나 클래스 등을 이용해 원하는 노드를 찾아주는 메소드<br><br>
element.getElementsByTagName('태그명')
: 주어진 태그에 해당하는 요소들의 컬렉션 반환<br>
element.getElementsByClassName('클래스명')
: 주어진 클래스 속성 값에 해당하는 요소들의 컬렉션을 반환<br>
document.getElementsByName('name명')
: 아주 드물게 쓰이는 메소드로 문서 전체를 대상으로 검색을 수행<br>
검색 기준은 name 속성 값이고 검색 결과를 담은 컬렉션을 반환
</p>
<h3>1) 태그명으로 접근</h3>
<ol>
<li><a href="#">목록1</a></li>
<li><a href="#">목록2</a></li>
<li><a href="#">목록3</a></li>
<li><a href="#">목록4</a></li>
<li><a href="#">목록5</a></li>
</ol>
<button onclick="accessTagName();">태그명으로 접근</button>
<script>
function accessTagName() {
let links = document.getElementsByTagName('a');
console.log('전달 받은 a 태그의 개수 : ' + links.length);
// 답 : 전달 받은 a 태그의 개수 : 5
let changeColor = 50;
for (let i = 0; i < links.length; i++) {
links[i].style.backgroundColor = 'rgb(130, 220,' + changeColor + ")";
changeColor += 50;
}
}
</script>
<h3>2) class로 접근</h3>
<script>
console.log(document.getElementsByClassName('area'));
// 답
// HTMLCollection(4) [div#area1.area, div#area1.area,
// div#area3.area, div.area, area1: div#area1.area,
// area3: div#area3.area]
</script>
<h3>3) name으로 접근</h3>
<form>
<fieldset>
<legend>취미</legend>
<table>
<tr>
<td>
<input type="checkbox" name="hobby" value="game" id="game">
<label for "game">game</label>
</td>
<td>
<input type="checkbox" name="hobby" value="music" id="music">
<label for "music">music</label>
</td>
<td>
<input type="checkbox" name="hobby" value="movie" id="movie">
<label for "movie">movie</label>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="hobby" value="book" id="book">
<label for "book">book</label>
</td>
<td>
<input type="checkbox" name="hobby" value="exercise" id="exercise">
<label for "exercise">exercise</label>
</td>
<td>
<input type="checkbox" name="hobby" value="etc" id="etc">
<label for "etc">etc</label>
</td>
</tr>
</fieldset>
</form>
<button onclick="accessName();">name으로 접근</button>
<script>
function accessName() {
let hobby = document.getElementsByName('hobby');
let checkedItems = '';
for (let hb of hobby) {
if (hb.checked) { // 체크 박스가 체크되어 있다면 true 리턴
checkedItems += hb.value + " 선택함\n";
}
}
alert(checkedItems);
}
</script>
</body>
</html>
'웹개발 수업 > JavaScript' 카테고리의 다른 글
[Day +61 / Java Script 과제]숫자&문자&날짜, 요소 검색 과제 (0) | 2021.09.17 |
---|---|
[Day +61 / Java Script]기초(12. 주요 노드 프로퍼티) (1) | 2021.09.17 |
[Day +59 / Java Script 과제]배열2, 객체 (0) | 2021.09.14 |
[Day +59 / Java Script]기초(8. 객체) (0) | 2021.09.14 |
[Day +58 / Java Script 과제]함수, 배열 (0) | 2021.09.13 |