
```jsx
-객체 리터럴을 const 변수 sana에 대입 - 객체이름:sana
- key: value ->map과 유사
const sana = {name:'사나', age:23, address:'경기'}
-구성요소가 없는 객체리터럴 선언
const momo= {}
momo.color = 'red';
-객체의 메소드는 함수 리터럴(문자)로 정의
sana.hello = function(){
alert(`안녕하세요. 나는 ${this.name}입니다.`)}
```| Operator | Description |
|---|---|
| + | Addition |
| - | Subtraction |
| * | Multiplication |
| ** | Exponentiation (ES2016) |
| / | Division |
| % | Modulus (Division Remainder) |
| ++ | Increment |
| -- | Decrement |
| Operator | Description |
|---|---|
| && | logical and |
| ! | logical not |
switch(operator.value){
case '+':
// +는 캐스팅안하고 할 수 있는 연산인 문자열 연결을 실행함
//강제 캐스팅
temp =Number(op1.value) + Number(op2.value)
break;
case '-':
// 문자열을 연산에 맞게 자동 캐스팅함
temp = op1.value - op2.value
break;| Operator | Example | Same As |
|---|---|---|
| = | x = y | x = y |
| += | x += y | x = x + y |
| -= | x -= y | x = x - y |
| *= | x *= y | x = x * y |
| /= | x /= y | x = x / y |
| %= | x %= y | x = x % y |
| **= | x **= y | x = x ** y |
| Operator | Description |
|---|---|
| == | 값 동등 비교 |
| === | 값과 형식 동등 비교 |
| != | 값 불일치 비교 |
| !== | not equal value or not equal type |
| > | greater than |
| < | less than |
| >= | greater than or equal to |
| <= | less than or equal to |
| ? | ternary operator |
getElementById 대신 css에서 사용했던 선택자로 요소 가져오기-> querySelector 한개만/ querySelectorAll 여러개 가져오는 메소드
const trOne= document.querySelector('tr')
console.log(trOne)
const trMany= document.querySelectorAll('tr')
console.log(trMany)
기본은 아직 정의되어 있지 않은 함수는 호출할 수 없음
단, function 함수이름() {}로 정의된 함수(1번)는 함수 끌어올리기라는 걸 함 (hoistiong) → 함수 위에서도 사용 가능
함수 밖에서 값을 선언하면 화면이 만들어지는 순간 만들어지기에 값이 없는 상태로 저장됨-> 값을 담고 싶으면 함수 안에 선언해야함
문법적인 규칙은 2,3번이 주로 쓰임.. 각각의 사용 필요가 있음
인자값 없거나 부족하면 연산 못함 (NaN)
action 속성값: 입력값을 받을 서버의 url
빈공간 조건식
if (name.value == '')
형식
let result =0;
result = myfuncA(3,1);
console.log('@@@ myfuncA 리턴 =', result)
// result = myfuncB(3,"2") //오류는 없지만 + 대신 문자열 연결연산합니다.
// console.log('@@@ myfuncB 리턴 =', result)
// 기본형식 1
function myfuncA(x,y) { // 인자가 2개
let temp = x * 10 + y; // 샘플 수식
console.log("myfuncA 실행하기!!")
console.log("리턴값 = "+temp)
return temp; }
// 기본형식 2 - 함수를 값처럼 변수 const에 대입
const myfuncB = function(x,y){
let temp = x * 10 + y;
console.log("myfuncA 실행하기!!")
console.log("리턴값 = "+temp)
return temp;}
// 형식3 - 화살표 함수(arrow function). 메소드의 인자가 함수 일 때 많이 사용
const myfuncC = (x,y) => {
let temp = x * 10 + y;
console.log("myfuncA 실행하기!!")
console.log("리턴값 = "+temp)
return temp;}
선택된 값 저장하기 + 유효성 검사
function save(){
const name = document.querySelector('input[name="name"]')
const age = document.querySelector('input[name="age"]')
const temp = document.querySelectorAll('input[type="checkbox"]')
const hobbies = document.querySelectorAll('input[type="checkbox"]:checked')
console.log(name.value)
console.log(age.value)
temp.forEach((ele,i)=> console.log('checkbox',i,'=',ele.value))
hobbies.forEach((ele,i)=> console.log('checkbox.cheked',i,'=',ele.value))
// 사용자 양식에는 필수 입력 항목이 있음. ->이름 ,나이 .. (유효성 검사)
//입력값에 대한 검사를 함 -> 함수 안에 넣어서..
if(name.value ==''){
alert('이름을 입력하세요')
name.focus() //해당 칸으로 포커스가 감
return; //함수 종료
}
if(age.value ==''){
alert('나이를 입력하세요')
age.focus()
return; //함수 종료
}
let hobbStr =''
const hobbArr = []
hobbies.forEach(ele=>{
//console.log(ele.value)
hobbArr.push(ele.value)
console.log(hobbArr)
})
hobbStr=hobbArr.join(',') //기호 , 로 배열값들 연결하기(join 메소드는 문자열 리턴)
//alert(`${name.value}님(${age.value})이 선택한 취미는 ${hobbStr}입니다`)
alert(`${name.value}님(${age.value})이 선택한 취미는 ${hobbArr.join(',')}입니다`)
alert('입력데이터 저장완료')
}
document.getElementById('lblEmail')
document.getElementsByTagName('input')
document.querySelector('#lblAge')
document.querySelectorAll('label')
document.forms document.forms[0] : form 들 중에서 0번 인덱스 가져오기
정규식을 이용하여 /[]/ 기호 안에 원하는 패턴 작성 []안에는 사용가능한 문자를 나열.
let regex= /[a-zA-Z가-힣]+/
let regex= /^[a-zA-Z가-힣]$/ -> ^$는 원래 사용해야하나 생략가능
1번이상 반복가능한 패턴기호는 +(중복입력가능)
? -> ()로 묶여있는 부분 사용 한번 또는 사용 안함
한번이상 사용 가능
이름에 대한 유효성 검사: 영문자 또는 한글만 가능 → 정규식 패턴을 이용
regex.test(name.value) -> 홍길동 true, 홍길동12 false
if(regex.test(name.value)) 참일경우
if(!regex.test(name.value)) 거짓일경우
핸드폰 번호 정규식
var regPhone = /^01([0|1|6|7|8|9])-?([0-9]{3,4})-?([0-9]{4})$/
이메일 정규식
var regEmail = /^[0-9a-zA-Z](notion://www.notion.so/%5B-_%5C.%5D?%5B0-9a-zA-Z%5D)*@[0-9a-zA-Z](notion://www.notion.so/%5B-_%5C.%5D?%5B0-9a-zA-Z%5D)*\.[a-zA-Z]{2,3}$/
특수문자 정규식
let regPw = /[!@#$%^&*(),.?":{}|<>]/;
<button id="executeBtn" onclick="calculate()">실행</button> -> () 주의!!비활성화 코드
.disabled
const bulb = document.getElementById('bulb')
const on= document.getElementById('on')
const off= document.getElementById('off')
off.disabled = true
function bulbon(){
bulb.src="../image/KakaoTalk_20240213_160833779.gif"
// 요소의 disable 속성을 설정
on.disabled = true //비활성화
off.disabled= false //활성화
}
현재날짜와 시간: new Date()
document.writeln(new Date())
-Locale: 국가 혹은 언어와 관련된 정보(en-US, ko-KR..)
운영체제에 설정한 현지시간을 현지 형식에 맞게 출력 (03/10/2025 ... )
document.writeln('toLocaleString = ',new Date().toLocaleString());
document.writeln('toLocaleDateString en = ',new Date().toLocaleDateString('en-US',{year:'numeric',month:"2-digit", day:"2-digit"}));
document.writeln('toLocaleDateString kr = ',new Date().toLocaleDateString('kr-KR',{year:'numeric',month:"2-digit", day:"2-digit"}));
document.writeln('toLocaleDateString zn-CN = ',new Date().toLocaleDateString('zn-CN',{year:'numeric',month:"2-digit", day:"2-digit"}));
-표준시간 출력
document.writeln('toUTCString(협정 세계시)= ',new Date().toUTCString());
document.writeln('toISOString(국제 표준형식)= ',new Date().toISOString());
-날짜 및 시간 GET 메소드</h4>');
document.writeln('년도 = ',new Date().getFullYear());
document.writeln('월 = ',new Date().getMonth()+1); //월이 0부터 시작함
document.writeln('일 = ',new Date().getDate());
document.writeln('요일 = ',new Date().getDay());//요일 0~6. 0=일요일
document.writeln('시 = ',new Date().getHours());
document.writeln('분 = ',new Date().getSeconds());
document.writeln('초 = ',new Date().getMilliseconds());
-날짜 및 시간 SET 메소드
setXXX메소드로 today에 저장된 날짜 변경 가능
let today=new Date();
today.setFullYear(today.getFullYear()+3)
document.writeln('today.getFullYear()+3 = ', today);
today.setMonth(today.getMonth()+4)
document.writeln('today.getMonth()+4 = ', today);
today.setDate(today.getDate()+10)
document.writeln('today.getDate()+10 = ', today);
-원하는 날짜로 설정
let mybirth = new Date('2020-11-03')-날짜를 전달하면 yyyy-mm-dd 패턴의 문자열로 리턴해주는 함수
function Dateformat(vdate){ //vdate->날짜타입 인자
const year = vdate.getFullYear();
const month = (vdate.getMonth()+1).toString().padStart(2,'0'); //month는 int, 문자열 수정은 String 일때 가능
const date = vdate.getDate().toString().padStart(2,'0'); //padStart ->무조건 2자리로. 없으면 0을 채워서
console.log([year,month,date].join('-'))} //[] 배열 값을 기호 -로 연결
Dateformat(new Date())
1)숙박일수 선택시
document.getElementById('night').addEventListener('change', changeEndDate)
2) 입실날짜 선택시
document.getElementById('enterDate').addEventListener('change', changeEndDate)
function changeEndDate() {
console.log('선택 숙박일 =', night.value)
let end_date = new Date(start.value)
end_date.setDate(end_date.getDate()+Number(night.value))
end.value = dateFormat(end_date) } // //퇴실날짜 input은 전역변수 end로 선언
-입실날짜 요소의 min,max 속성으로 값의 제한을 설정
-요구사항 min: 오늘날짜 / max : 3개월
function initStart(){
let today = new Date();
start.value = dateFormat(today);
start.min = start.value; //오늘날짜 이전 선택 불가
today.setMonth(today.getMonth()+3) //3달 이후까지만 선택 가능
start.max = dateFormat(today)} 26_dateForm-T.html<pre style="font-size: 1rem; font-family: inherit;">schedules.sort(function(a,b){
//비교되는 2개의 a 객체와 b 객체
-비교 속성에 대한 조건식
-시간 순서로 정렬시
if(a.time < b.time)
-할일 순서로 정렬시
if(a.todo < b.todo)
return-1
else return 1 })-배열 선언
const names = []; -> 내용이 없는 배열 선언
const arrr=['a',123,new Date()]; // 배열값 형식이 달라도 저장할 수 있음
//names = ['a','b'] -> 오류.. -> 배열자체를 바꿀 수 없음
-배열로 바꾸기
const liArr = Array.from(lis) -item은 li 요소
-배열 값 삽입
names.push('사나') //const 배열이 배열 요소 변경은 할 수 있음, 하나씩만 입력 가능
names.push(100) //동일한 배열에 문자열과 number 저장가능
document.write('<h3>names 배열요소</h3>')
document.writeln("names= ",names) //ln은 엔터. 엔터는 html에서는 줄바꿈 안함
const objarr = [momo, sana]; //객체의 구성요소가 다르지만 같은 배열에 저장 가능 (배열[] 과 오브젝트{ } 공존 가능)
-pop
names.pop() //마지막 인덱스 요소를 제거
-splice: 배열 요소의 삭제 - 위치와 개수 지정
names.splice(3,1) //위치 3, 개수 1
names.splice(3,2) //위치 3, 개수 2
-배열의 크기
document.writeln("names 크기 = ",names.length)
-요소값 찾기
모모의 위치 찾기
document.writeln(names.indexOf('모모'))
배열에 모모가 있는지
document.writeln('names.includes(\'모모\')=',names.includes('모모'))
names.forEach(function(item,index,array){
document.writeln("item=", item)
document.writeln("index=", index)
document.writeln("array=", array)
})
화살표함수로 변경1
names.forEach((item) => {
document.writeln("item=", item)
})
화살표함수로 변경2
화살 함수를 변수로 선언. 함수 실행코드가 1줄일 경우 {} 생략
const printItem = (Item) => document.write("Item: ",Item)
names.forEach(printItem)
item을 매개변수로 삼음..배열의 정렬: times.sort();
js 에서는 문자열도 크다, 작다 기호로 비교 가능
schedules.sort(function(a,b)) → 비교되는 2개의 a 객체와 b 객체
--비교 속성에 대한 조건식
-시간 순서로 정렬시
if(a.time < b.time) return-1
else return 1 })
-할일 순서로 정렬시
if(a.todo < b.todo) return-1
else return 1 })
-이벤트 처리방법 1
<button id="hello" onclick="hello()">Hello</button>
function hello(){
alert("hello")
console.log('클릭 이벤트에 대한 함수입니다 button 태그에 hello() 함수 호출 명령이 있습니다.')}
-이벤트 처리방법 2 / 서로의 영역을 침범하지 않고 처리 가능
<button id="hi">하이</button>
<pre style="font-size: 1rem; font-family: inherit;">
document.getElementById('hi').addEventListener('click',
function(){
alert('하이')
console.log('button 태그에 자바스크립트 코드를 작성하지 않고 이벤트 처리합니다')})
-2-1 addEventListener의 종류 (change, click, keyup, keydown..)
1) change: 요소의 값이 변경될 때 발생하는 이벤트 , input에서는 내용이 바뀌는 이벤트
2) click: 마우스 input을 클릭시 발생하는 이벤트
document.getElementById('message').addEventListener('change',()=>{
const msg = document.getElementById('message')
console.log(msg.value)})
3) keyup->눌렀다 뗄때(aaaaaaa ....),
4) keydown->입력(누를떄 - a) -> 비슷함
document.getElementById('message').addEventListener('keyup',()=>{
const msg = document.getElementById('message')
console.log(msg.value) })
document.getElementById('container').addEventListener('click',function(e){
console.log(e)
console.log('e.target.tagName=', e.target.tagName)
if(e.target.tagName==='SPAN'){
//alert(`선택한 공은 ${e.target.outerText}입니다.`)
alert(`선택한 공은 ${e.target.innerHTML}입니다.`)}})document.forms[0].age : 지정된 form에서 name 속성 age 가져오기
document.forms[0].age.value : 가져온 input 요소의 value document.forms[0].name.valuedocument.forms[0].hobby
document.forms[0].hobby[0].value => 요소 인덱스 지정해야 value 를 알 수 있음
document.forms[0].hobby[1].value
document.forms[0].hobby[2].value
document.forms[0].hobby.value => '' 비교: radio 버튼
document.forms[0].gender => 요소들 배열
document.forms[0].gender.value => 선택한 값 리턴required나 email 타입 체크는 태그에 설정한 것으로 submit되기 전에 동작, onsubmit 함수 실행 전에 동작
<input type="text" name="name" id="" placeholder="이름을 입력하세요" required>
submit
18번
1. form: 입력데이터 서버로 전송하기- onsubmit 활용(버튼은 submit동작)
<!-- 17번 파일에서 form 태그 사용이 추가됨 -> 버튼의 동작이 submit이 됨 -->
<!-- action 속성값: 입력값을 받을 서버의 url -->
<!-- onsubmit 속성: submit 이벤트 발생시 실행할 js 코드(혹은 함수)
함수 return이 false이면 action으로 넘어가지 않음 ->false로 만들어서 넘어가지 못하도록 만들기 가능-->
--
19번
2. form: 입력데이터 서버로 전송하기2 - 자바스크립트에서 submit()메소드 활용 (버튼은 일반 button 동작)
<!-- button의 타입을 button으로 해서 동작시킬수도 있음 -->
<form action="../day3_form/success.html">
<button type="button" onclick="save()">저장하기</button>
if (age.value == '') {
alert('나이를 입력하세요');
age.focus();
isValid= false;}
if(isValid){ //, 유효성 검사가 모두 끝나고 isValid가 참일때만 form 제출
const hobbArr = []
hobbies.forEach(ele => {
hobbArr.push(ele.value)
console.log(hobbArr)})
alert(`${name.value}님(${age.value}) 선택한 취미는 ${hobbArr.join(',')} 입니다.`)
alert('입력 데이터 저장완료!!')
document.forms[0].submit();// 직접 submit동작 메소드}
required : 필수 입력 (submit일때만 동작)
기본 type= submit. 클릭하면 action에 저장된 url로 전송
input type="email" -> text 타입과 같음.. + @를 확인하는 기능 포함
<fieldset>
<legend>취미를 선택하세요</legend>
<input type="checkbox" name="hobby" id="swimming" value="수영">
<label for = "swimming">수영</label>
<input type="checkbox" name="hobby" id="ski" value="스키">
<label for = "ski">스키</label>
<input type="checkbox" name="hobby" id="football" value="축구">
<label for = "football">축구</label>
<input type="checkbox" name="hobby" id="baseball" value="야구">
<label for = "baseball">야구</label>
<input type="checkbox" name="hobby" id="running" value="달리기">
<label for = "running">달리기</label>
</fieldset> ->document.getElementsByTagName('h3') => 기본이 컬렉션(배열)을 리턴하는 메소드
document.querySelector('h3') => h3태그가 문서에 1개 있을 때만 querySelector 사용
document.querySelector('h3').innerHTML => h3태그의 콘텐츠(텍스트)
-요소의 style 변경이 가능.
document.querySelector('h3').style.color = 'blue' document.querySelector('h3').style.border = '1px solid gray' (백틱``) 기호 사용은 ${} 을 사용하기 위한 기호document.writeln([${item}])
document.writeln('['+item+']')