DB 쿼리문을 돌려야하므로 테스트 실행불가

 

 

 

<form>
	<input type="text" name="u_id" />
	<input type="button" value="아이디 중복 확인" onclick="openConfirmId(this.form)"/>
 </form>
    
    
  <script>
    function openConfirmId(inputForm) {
	         if(inputForm.u_id.value == ""){
	            alert("아이디를 입력하세요.");
	            return;    // 이 함수 강제종료
	         }
	         // 검사 팝업 열기 
	         let url = "confirmId.jsp?u_id=" + inputForm.u_id.value;         
	         open(url, "confirmId", "width=300, height=200, toolbar=no, location=no, status=no, menubar=no, scrollbars=no, resizable=no"); 
	      }
  </script>

 

 

 

 

// confirmId.jsp



<%@page import="team.user.model.UserDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>아이디 중복확인</title>
</head>
<%
	request.setCharacterEncoding("UTF-8"); 
	// open(url...) : url = confirmId.jsp?u_id=값
	String u_id = request.getParameter("u_id");
	// DB 연결해서 사용자가 작성한 id값이 db테이블에 존재하는지 검사 
	UserDAO dao = new UserDAO(); 
	boolean result = dao.confirmId(u_id); // true 이미존재함, false 존재X -> 사용가능 
%>
<body>
<%
	if(result) { // true -> 이미 존재 -> 사용불가  %>
	<br />
	<table>
		<tr>
			<td><%= u_id%>은/는 이미 사용중인 아이디 입니다.</td>
		</tr>
	</table> <br />
	<form action="confirmId.jsp" method="post">
		<table>
			<tr>
				<td> 다른 아이디를 선택하세요. <br />
					<input type="text" name="u_id" /> 
					<input type="submit" value="아이디 중복확인" />
				</td>
			</tr>		
		</table>
	</form>
		
<%	}else { // false -> 존재 X -> 사용 가능 %>
	
	<br />
	<table>
		<tr>
			<td>입력하신 <%= u_id%>은/는 사용 가능합니다. <br />
				<input type="button" value="닫기" onclick="setU_id()" />
			</td>
		</tr>
	</table>
		
<%	}%>

	<script>
		function setU_id() {
			// 팝업을 열어준 원래 페이지의 id input태그의 value를
			// 최종 사용할 id로 변경. 
			opener.document.inputForm.u_id.value = "<%= u_id%>";
			// 현재 팝업 닫기. 
			self.close(); 
		}
	</script>
</body>
</html>
// DAO 쿼리문 매서드 


public boolean confirmId(String u_id) {
			boolean result = false;
			int u_idCount = 0;
			Connection conn = null; 
			PreparedStatement pstmt = null;
			ResultSet rs = null; 
			
			try {
				conn = getConnection(); 
				String sql = "select count(*) from signup where u_id=?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, u_id);
				rs = pstmt.executeQuery();
				if(rs.next()) {
					u_idCount = rs.getInt(1);
					System.out.println("u_idCount : " + u_idCount);
					if(u_idCount == 1) {
						result = true;
					}
				}

				
			}catch(Exception e) {
				e.printStackTrace();
			}finally {
				if(rs != null) try { rs.close();} catch(SQLException e) { e.printStackTrace(); }
				if(pstmt != null) try { pstmt.close();} catch(SQLException e) { e.printStackTrace(); }
				if(conn != null) try { conn.close();} catch(SQLException e) { e.printStackTrace(); }
			}
			
			return result;
		}

체크박스 선택시 제출버튼 활성화

 

 

 

 

 

 

 

Insert title here
[필수] 체크해야 제출가능

 

 

 


<form action="#" method="#" name="#" enctype="multipart/form-data" onsubmit="#">
	<input type="checkbox" name="agreements" onClick="agreeCheck(this.form)"> [필수] 체크해야 제출가능
	<input type="submit"  name="checkButton" value="등록하기"  disabled/>
</form>

<script>
    function agreeCheck(frm){
               if (frm.checkButton.disabled==true)
                frm.checkButton.disabled=false
               else
                frm.checkButton.disabled=true
     }
</script>

 

 

여러개의 경우

https://codesandbox.io/s/agreement-l5uc6?file=/src/index.js

버튼에다가 alert만 띄우면 파라미터가 넘어가질 않는데

 

submit에 alert 효과 만들기

 

<form action="#">
	<input type="text"/>
	<input type="file"/>
    <input type="submit" value="수정하기" onClick='return confirmSubmit()'/>
</form> 
    
    
    <script>
		function confirmSubmit()
		{
		var agree=confirm("정말 수정하시겠습니까?");
		if (agree)
			return true ;
		else
			return false ;
		}
	</script>

 

 

 

17. 이벤트 등록
1) 이벤트 등록 방법
addEventListener() 를 이용하여 요소에 이벤트 등록

타켓.addEventListener("이벤트종류",function(){});
이벤트 종류
load : 로딩이 완료 되었을때
resize : 윈도우창 크기 변경되었을때

keydown
keyup

change
click
focus
mousedown
mouseup
mouseout
mouseover
mousemove

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>
    </title>
</head>
<body>
  <button class="btn"> 클릭 </button>
  <button onclick="clickFunc()"> 클릭 2</button>
   <script> // 17 이벤트 등록
  
//@1 자바스크립트로 이벤트 등록
       const btn = document.querySelector(".btn");
       btn.addEventListener("click",function(){
           alert("버튼클릭");
       });
       
//@2 <button onclick="alert('버튼클릭)">클릭</button> 과 동일

//@3
       function clickFunc(){
           for(let i = 0; i <10; i++){
               if(i%2 ==0){
                   console.log("helloo"+i); 
               }
           }
       }
       
    </script>
    
</body>
</html>

16. 문서 객체 모델 (DOM, Document Object Model) : DOM 트리 

문서 노드  : 전체 문서를 가르키는 Document 객체
HTML 요소 노드 : HTML 요소를 가르키는 객체
텍스트 노드 : 텍스트를 가르키는 객체




# 노드 객체 가져오는 메서드 
document.getElementById(id값) : id 속성값으로 노드 가져오기
document.getElementsByTageName(name) : 태그명으로 노드 찾기 (배열로 리턴)
document.getElementsbyClassName(name) : class 속성값으로 노드 가져오기 (배열로 리턴)
document.querySelector(css선택자) : css 선택자로 노드 찾기 (첫번째 찾은 요소만 리턴)
document.querySelectorAll(css선택자) : css 선택자로 노드 찾기 (모든요소 배열로 리턴)

<h1>hello</h1>
# 찾은 HTML 요소 확인/수정
요소.innerText = '대치할 새로운 텍스트' : 요소 안의 내용 확인/ 수정 (태그 미포함)
요소.innerHTML = '새로운 HTML 내용' : 요소 안의 내용 확인/ 수정 (태그 포함)
요소.attribute = 새값 : 요소의 속성값 수정
요소.setAttribute(속성명, 값) : 요소의 속성값 메서드로 설정


# HTML 요소 생성/추가
document.creatElement(태그명) : HTML 태그 생성
document.appendChild(요소) : 요소 추가하기

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div class="first"> div 1 
          <div>1-1</div>
          <div>1-2</div>
          <div>1-3</div>
          <div class = "test"> test div</div>
      </div>
       
        <div id ="second"> div 2</div>
        <div id ="third"> div 3</div>
        <script>   
        
            let elem0 = document.getElementsByTagName('div'); // 태그 div 로된 모든 노드 출력  
            
            let elem1 = document.getElementsByClassName('first'); // 클래스 first 로된 노드 출력 
                console.log(elem0); // HTMLCollection(7) [div.first, div, div, div, div.test, div#second, div#third, second: div#second, third: div#third]
                console.log(elem1); // HTMLCollection [div.first]
            let elem2 = document.getElementById('second');
                console.log(elem2);
    
            let elem3 = document.querySelector('div.test');
                console.log(elem3);
    
            let elem4 = document.querySelectorAll('div');
                console.log(elem4);  //NodeList(7) [div.first, div, div, div, div.test, div#second, div#third]
                for(let i = 0; i<elem4.length; i++){
                console.log(elem4[i].innerText); // 글자만 가져오기
                }
                for(let i = 0; i<elem4.length; i++){
                console.log(elem4[i].innerHTML); // html 다가져오기
                }
    
                    
    </script>
</body>    
</html>

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .box{
            width : 100px;
            height: 100px;
            text-align: center;
        }
    
    </style>
</head>
<body>
       <h1>hello</h1>
       
       <script> // 16번 
        const newTag = document.createElement('div'); // div태그 스크립트로 생성
           newTag.innerText = 'JavaScript';
           newTag.setAttribute("class","box");
           newTag.style.background = "red";
           newTag.style.color = "white";
           
          document.body.appendChild(newTag);

        </script>

</body>
</html>

4) history 객체
: 브라우저에서 뒤로가기 앞으로가기 기능을 코드로 실행시키는 기능 제공

# 속성들 메서드
back() : 뒤로가기
forward() : 앞으로가기
go(이동숫자) : 이동 숫자를 -2로 입력하면 뒤로가기 2번 / 양수이면 앞으로가기

5) navigator 객체
: 현재 사용자의 브라우저 정보와 운영체제 정보를 제공

# 속성
appVersion : 사용자 브라우저 버전 정보 리턴
language : 사용자 브라우저가 사용하는 언어. 한글 'ko'
product : 사용자 브라우저 엔진 이름.
platform : 사용자 컴퓨터 운영체제 정보 제공.
onLine : 사용자 온라인 상태 여부 제공.
userAgent : 사용자 브라우저와 운영체제의 종합 정보 제공

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>
    </title>
</head>
<body><!-- 15-4 -->
           <h1> page 1</h1>
           <button onclick = "location.href='js25.html'"> 2 page로 이동</button>
           <button onclick="history.forward()"> 앞으로가기</button>
           <button onclick="history.go(1)"> 앞으로가기 go + 1</button>
    
     <script> 
        
             // 15- 5 네비
             let userAgent = navigator.userAgent;
             document.write(userAgent);
        
    </script>
    
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
   <h1>page2</h1>
   <button onclick="history.back()">뒤로가기</button>
    
</body>
</html>


userAgent 출력문 :
     Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) 
Chrome/102.0.0.0 Safari/537.36


화면출력문 내용
Mozilla/5.0 기본 플랫폼
(Windows NT 10.0; Win64; x64)  운영체제 정보
AppleWebKit/537.36 (KHTML, like Gecko)   사용중인 브라우저 엔진 이름
Chrome/102.0.0.0  사용중인 브라우저 이름 / 버전
 Safari/537.36      같은 엔진을 사용중이며 호환 가능한 다른 브라우저





15. 브라우저 객체 모델 (BOM, Browser Object Model)
: 브라우저에 내장된 객체가 계층적 구조로 이루어져있는 것을 말함



1) window 객체

# 메서드
*open("URL", "새창 이름", "새창 옵션들") : 팝업창
* 새창 옵션들 *
width  : 창 너비
height  : 창 높이
left : 창 x 축 좌표
top : 창 y 축 좌표
scrollbars : 스크롤바 숨김 / 노출 설정. no/yes
location : url 주소 입력하는 영역 숨김/노출 설정
status   : 상태 표시줄 영역 숨김/ 노출 설정
toolbars : 도구 상자 영역 숨김/ 노출 설정

alert(data)  : 경고창에 data 보여주기
confirm("질문") : 질문 확인/취소. 확인 : true 리턴, 취소 : false 리턴
prompt("질문", "기본 답변")  :입력창
moveTo(x,y) : 지정한 새창의 위치를 이동
resizeTo(width, height) : 창크기 변경
*setIntervar(funtion(){}, 시간간격) : 지속적으로 지정한 시간간격을 두고 함수실행

*clearInterval() : 인터벌 삭제
*setTimeout(funtion(){...}, 시간간격)  : 지정한 시간 이후 함수 한번 실행
*clearTimeout() : 타임아웃 삭제

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
   <button onclick="window.clearInterval(inter)"> 정지 </button>
 <button onclick="window.clearTimeout(out)"> 타임아웃 취소 </button>
         <script> //15 - 1
       
       // 5초후 타임아웃 콘솔창에뜸
        let out = window.setTimeout(function(){
            console.log("타임아웃!!!!");
            
        }, 5000);
        
        /*
        // 콘솔창에 1초마다 숫자만들기
           let num = 0;
            let inter= window.setInterval(function(){
                num++;
                console.log(num);
            },1000);
       */
        

        /*   // 네버버어라는 네이버창을 해당 크기에 맞게 띄움
            window.open("http://naver.com","네버버어","width=350, height=400, left=50, top 50, location=no, scrollbars=no,status=no");
        */
        /*   // 미리만들어둔 js22pop 파일을 popup이란 이름으로 해당 크기에 맞게 띄움
            window.open("js22pop.html","popup", "width=300, height=300, left=100,top=100, location=no ");
        */
        /*   // 지금 배고픈가요라는 질문창을 띄움
            let result = window.confirm("지금 배고픈가요?");
            console.log(result);
        */

    
    </script>
</body>
</html>

2) 스크린 객체
: 사용자의 모니터 정보를 제공하는 객체

screen.속성;

width  : 화면 너비값 리턴
height  : 화면 높이값 리턴
availWidth  : 작업표시줄 제외한 화면 너비값
availHeight : 작업표시줄 제외한 화면 높이값
colorDepth : 사용자 모니터가 표현 가능한 컬러bit리턴

3) location 객체
(브라우저 주소창 관련)

# 속성과 메서드 
**href** : 주소 영역의 주소를 설정하거나 리턴
hostname : url의 호스트이름을 설정하거나 리턴
host : url의 호스트이름과 포트번호를 리턴
protocol : 프로토콜 리턴
search : url의 쿼리스트링 리턴 (쿼리스트링 = 주소의 ? 뒷부분)
reload() : 브라우저 새로고침

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body> <button onclick="location.href='js22pop.html'"> 새로고침 </button>
    <script> // 15 -2 
    
        console.log(screen.width);    // 1920	
        console.log(screen.height);	   // 1080
        console.log(screen.availWidth); //1920
        console.log(screen.availHeight); //1040
        console.log(screen.colorDepth); 	//24

    
        //15 -3
        let hrefval = location.href;
        console.log(hrefval);     //http://127.0.0.1:51856/Js/js23.html
        
        console.log(location.hostname); // ip
        console.log(location.host);     //ip + 포트
        console.log(location.protocol);     //http(s)
        console.log(location.search);       //주소창? 뒤 리턴
        
        let tout = setTimeout(function(){
            //location.href = "js22pop.html";
            location.reload();
            
        },3000);   // 3초마다 새로고침
        
        
    </script>
</body>
</html>

14. 내장 객체 (Built-in Object)

1) 객체 생성
변수명 = new 생성함수();

2) Date 객체
: 날짜나 시간 관련 정보 필요할 때 사용

#1. 객체 생성
변수 = new Date(); 
변수 = new Date("연/월/일");  문자열
변수 = new Date(연, 월-1, 일, (시간, 분, 초, 밀리초 등 더 쓸 수 있다)); 

#2. 메서드

- 정보 가져오기
getFullYear()  : 연도 정보
getMonth()     : 월 정보 ( 0월~11월) 
getDate() : 일 정보
getDay() : 요일 (일:0~ 토:6)
getHour() : 시간정보
getMinutes() : 분
getSeconds() : 초
getMilliseconds() : 밀리초
getTime() : 1970.1.0.0.0부터 경과된 시간을 밀리초로 리턴

- 정보 수집
setFullYear()  : 연도 수정
setMonth()     : 월 수정 ( 0월~11월) 
setDate() : 일 수정
- : 요일은 날짜 바꾸면 자동으로 바뀜 (일:0~ 토:6)
setHour() : 시간정보 수정
setMinutes() : 분 수정
setSeconds() : 초 수정
setMilliseconds() : 밀리초 수정
setTime() : 1970.1.0.0.0부터 경과된 시간을 밀리초로 수정

3) Math 객체
수학 관련 기능과 속성을 제공하는 객체

Math.상수
Math.메서드()

4) Array 객체 : https://itcreator.tistory.com/36
5) String 객체
: 문자형 데이터를 취급하는 객체

변수 = "문자열"; 변수 = '문자열';
변수 = new String("문자열");

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <script> // 14-2 ~ 3설명
            let today = new Date();
            console.log(today);
        
            //let christmas = new Date("2022-12-25"); 값 동일
            let christmas = new Date("2022/12/25"); 
            console.log(christmas);
        
            let offday = new Date(2022, 6, 6); //7월 6일
            console.log(offday);
        
            // 메서드
            let month = today.getMonth(); // -1 해서 줌
            console.log(month+1);
        
            let day = today.getDay();
            console.log(day);
        
            let date = today.getDate();
            console.log(date);
        
            let time = today.getTime();
            console.log(time);
            console.log(christmas);
        
            christmas.setFullYear(2023);  // 년도 수정
            console.log(christmas);
        
            christmas.setDate(24);      // 날짜 수정
            console.log(christmas);
        
        
            //14-3 Math
          //  let rd = parseInt(Math.random()*10); / 0~9 사이값 
         //   console.log(rd*100);
        
            // 14-5 String
            let str = "hello javascript"
            console.log(str.charAt(0)); // h 가져옴
            console.log(str.indexOf('j')); //6 (띄워쓰기도 문자)
            console.log(str.match("hello")); // 같은 문자열이 있나?
            console.log(str.substr(3, 5)); // lo ja (시작인덱스, 글자수)
            console.log(str.substring(3, 5)); // lo (시작인덱스, 끝인덱스):끝인덱스 전까지 
            console.log(str.replace("hello","awesome")); //awesome javascript
            console.log(str.split(" ")); //['hello', 'javascript']
    </script>
</body>
</html>

13. 자바스크립트 객체
: 프로퍼티와 메서드로 이루어짐 
프로퍼티(변수의 일종) : 프로퍼티(키)와 프로퍼티값(value)로 구성
프로퍼티키는 일반적으로 문자로 구성하고 값은 원하는 값
메서드 : 객체 안에 있는 함수를 가르킴

   
HTML 태그 속성(attribute)과 속성값을 가진다
CSS  프로퍼티와 프로퍼티값
JavaScript  프로퍼티와 프로퍼티값, 그리고 메서드로 이루어짐




1) 사용자 객체 
JS 객체 생성 방법
#1. 객체 리터럴 방식 : 객체 구분 기호 : {}
변수 = {
프로퍼티명 : 값, 
프로퍼티명 : 값,.....
};
객체 자체의 주소값이 바뀌어야만 let으로 변수에 담고
객체 자체의 주소값은 안바뀌고 안에만 바꾼다면 const 변수에 주로 담음

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
   <script>  //13 객체 리터럴 방식
            const user= {name :"pika",age : 10}; // , 을 통해 객체구나 생각!
            console.log(user);
            console.log(user.age);
            console.log(user.name);
       
            console.log(user.test); // 없는 프로퍼티 읽으려하면 undefined 리턴함.
       
       
            // 빈 객체 만들기
            const obj = {};
    //   자바로 치자면 class test {}
    //   obj = new test {}
    
            // 프로퍼티 추가, 삭제  (자바에서 hashmap이랑 비슷함)
       obj.addr = "서울시 서초구";
       console.log(obj);
       delete obj.addr;
       console.log(obj);
       
            // in 연산자로 프로퍼티 있는지 확인
       console.log("name" in user);  //true 출력
       console.log("test" in user);  // false 출력
       console.log("toString" in user);  // true 출력
       
    </script>
    
</body>
</html>

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    
    <script>
            // 13. 리터럴 객체  (익명함수)
                let person = {
                    name : "pika",
                    age : 10,
                    getData : function(){
                        console.log("hello method");
                    }, 
                    test : {a: 10, b : "haha", c : [1,2,3,4], d : function(abc){}}
                };
    
            console.log(person);
            console.log(person.age); //변수 출력
            person.getData(); // 메서드 호출
            
        console.log(person.test.a);
        // 3 출력
        console.log(person.test.c[2]);
        console.log(person.test.d(10));
        
            // 프로퍼티 (변수) 추가 : 없는 이름의 프로퍼티명에 값대입
        person.height = 170;
            // 메서드 추가 : 없는 이름의 프로퍼티명에 익명함수 대입
        person.getSum = function(a,b){
            return a + b;
        };
        console.log(person);
        console.log(person.height);
        console.log(person.getSum(10,20));
        
    </script>  
</body>
</html>

 


#2. new Object()로 생성하는 방식
const 변수 = new Object();
변수.age = 10;
변수.name = "hello";

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <script>    // 13- 2 new object로 객체생성
                    const person = new Object();
                    person.name = "pikapika";
                    person.age = 100;
                    person.getNum = function(){
                        console.log("getNum 메서드호출");
                        return "haha";
                    };
                
                    console.log(person);
                    let result = person.getNum();
                    console.log(result);
 
    </script>
</body>
</html>



#3. 생성자 함수로 생성하는 방식
# 생성자 정의
fuction 생성자명(){ // 생성자명은 첫글자 대문자
....
}
# 객체 생성해서 사용
const 변수 = new 생성자명();
변수.~~~~~
#4. ES6와 클래스

class 클래스명 { // 클래스명 첫글자 대문자
constructor(){// 생성자
....
}
}

const 변수 = new 클래스명();

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
       <script> // 13 -3 
          /*  function Person(name, age){  //대문자
                console.log("Person 객체생성");
                this.name = name;
                this.age = age;
            }
        
            const pika = new Person("pika", 10);
           console.log(pika);
           
          */
                // 13 -4
            class Person{
                constructor(name){
                    console.log("hello");
                    this.name = name;
                }
            }
           class Student extends Person{
               constructor(name, age){
                   super(name);
                   this.age = age;
               }
           }
           
           //const p = new Person("pika");
           // console.log(p);
           
            const stu = new Student("kobugi", 100);
            console.log(stu);
    </script>
    
</body>
</html>

 

12. 자바스크립트 변수 선언 방식
: 변수 선언 방식에는 var / let / const 와 같이 3가지로 선언 가능 (ES6부터 가능)
-> 변수 이름 충돌로 인하여...


ECMAScript ES6 = ECMAScript 표준의 6번째 에디션 (2015)

* 블록스코프 : {} if, for, function
함수스코프 : 블록스코프 중 함수 범위를 갖는 스코프

1) var  : 함수스코프 : 같은 이름의 변수 재선언 가능.  (var a = 10; var a = 20; 이렇게 선언가능)
2) let  : 블록스코프 : 같은 이름의 변수 재선언 불가능. 값수정 가능 (자바와 동일)
3) const: 블록스코프 : 재선언 불가능. 값수정 불가능 -> 상수
const는 선언과 동시에 값을 할당해야함. 아니면 에러 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    
    <script>  //12 자바 변수
        //var
        /*var name = "피카츄";
        console.log(name);
    
        var name = "꼬부기";
        console.log(name);
        */
        
        //let
     /*   let name =  "피카츄";
        console.log(name);
        
        let name = "꼬부기";  //실행 불가
        console.log(name);
       
        name = "haha"
        console.log(name);   // 수정가능
        */
        
        //const
        const name = "피카츄"
        console.log(name);
        
      //  const name = "꼬부기" // 실행 불가
       // console.log(name);
        
        name = "sdsdf"   // 수정 불가
        console.log(name);
        
          var a;
         var b;
         const c = a;
         
    </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    
    <script>
        /*
            // var 함수 스코프
            var foo = "문자문자"
            if(typeof foo == "String"){
                var result = true;
            }else{
                var result = false;
            }
            
            console.log(result); //true 나옴 (사용가능)
        */
        
            var foo = "문자문자"
            if(typeof foo == "String"){
                let result = true;   //
            }else{
                let result = false;
            }
            
            console.log(result); // 에러뜸 ( 사용불가)
    
    </script>
    
</body>
</html>

11. 함수 리터럴과 익명함수
1) 리터럴
: 자바 스크립트에서 데이터를 만드는 방법은 크게 두가지로,
리터럴 방식과 객체 방식 두가지가 있다.


타입 리터럴 방식  
숫자  var num=10;  var num = new Number(10);
문자 var name="abc" var name = new String("abc");
불린 var play= true; var play = new Boolean(true);
배열  var arr=[1,2,3];  var arr = new Array(1,2,3);


2) 함수 리터럴
: 함수 이름을 주지 않고 만들면 됨.

#1. 일반적인 방법
function hello(){
.....
}

#2. *리터럴*
var hello = function(name){
....
}
#3. 객체방식(잘안씀)
var hello = new function("name","실행할 명령문들");

3) 익명함수
: 리터럴 방식의 함수를 익명함수라 한다.
호이스팅 불가능
일반함수 : 재사용 많이   할 경우 
익명함수 : 재사용 비중이 적거나, 값처럼 정의해서 넘겨줘야할 경우

익명 함수 활용 전  익명 함수 활용 후
function hello(){
    alert("안녕하세요");
}
$("#btn").click(hello);
$("#btn").click(function(){
    alert("안녕하세요");
});

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    
    <button id="btn">클릭</button>
    <script>
        // 리터럴
        var hello = function(name) {
            console.log(name + "님 배고프신가요?");
        }
        
        hello("토피"); 
        
        // 익명함수 
        $(document).ready(function(){
            $("#btn").click(function(){
                alert("안녕하세요");
            });        
        }); 
   
    </script>
    
</body>
</html>

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    
    <script>
        //console.log(a);
    
        //a = 10;  // 전역변수로 선언+대입 해줌 
        //console.log(a);
    
        var a = "global";
        
        function f() {
            a = "local"; // 함수 안에서 var 생략하면 전역으로 선언됨.
            console.log("f : " + a);
        }
        f(); 

        console.log(a);
        
    </script>
     
</body>
</html>

10. 함수
1) 함수 function  //자바에서는 메서드와 같은 역할
특성 기능을 하는 코드들을 묶어서 독립된 부품으로 만들어 재사용하고자 할때
호출하여 사용하는 기능

2) 구조 
# 정의(매개변수x, 리턴 x)
function 함수명(){
//실행코드들...
}
#호출
함수명();

# 정의(매개변수O, 리턴 x)
function 함수명(변수명, 변수명,....){
//실행코드들...
return 값;
}
#호출
변수 = 함수명(인자,인자,...);

 

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
   <script>
        // 함수정의
        function test(){
            document.write("hello <br/>");
            document.write("hello <br/>");
            document.write("hello <br/>");
            
        }
        // 함수 실행
       test();
        
        function test2(name, age){
            document.write("당신의 이름은" + name + "이고, 나이는 "+ age + "살 입니다");
            }
       test2("피카츄",20);
       test2("홀길동",100);

    </script>
    
</body>
</html>

 

 

 


3) 스코프
   : 변수 또는 함수의 유효범위 말함

            #1. 전역 변수 Global Variable
선언위치 : 함수밖, {}밖
사용범위 : 자바스크립트 전체 영역

             #2. 지역 변수 Local Variable
선언위치 : 함수안 
사용범위 : 함수안

* 함수 내에서 동일 이름의 변수에 대한 우선순위 : 지역 > 전역

            #3. 전역 함수
전역변수와 동일

             #4. 지역 함수
정의 위치 : 함수안
사용 범위 : 정의된 함수를 품고 있는 함수안

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>
    </title>
</head>
<body>
    
    <script>
        var num = 10; // 전역변수
        console.log(num);
        
        function test(){
            console.log("function : " + num); // 전역 num 10출력
             num = 20; //함수안에서 var 생략하면 전역으로 선언됨;
            
            //var num = 20; //지역변수
           
            console.log("function : " + num); //지역변수 20 나옴
            
            //var num = 100; //지역
            //console.log("function : " + num);
        }
    
       // test()  //실행시 16번째 num 이 실행되어 전역변수로 20이 선언됨
        
        console.log(num);  
    </script>
    
</body>
</html>

 

 

 

test() 실행시 전역변수 값이 바뀜

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
   <script>
       // 전역함수
       function func(){
            console.log("전역함수!!");
        }
        
       //전역
    function outerFunc(){
        //지역
        function innerFunc(){
            console.log("")
        }
        
        innerFunc();
    }
    func();
    outerFunc;   
    // innerFunc; 실행안됨    
    
    </script>
    
</body>
</html>


4) 변수에 함수 저장하기
:자바스크립트에서는 함수도 변수에 저장가능.
변수에 함수를 저장하면 변수 이름을 함수처럼 사용할 수 있다.

var 변수명 = 함수명;
-> 변수명();

 

5) 매개변수 값으로 함수 사용하기
: 매개변수도 변수이기 때문에 함수를 담을 수 있다.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>
    </title>
</head>
<body>
    <script>
        /* 함수를 변수에 담을 수 있다.
        function hello(name){
            console.log("hellooo"+ name);
        }
        hello("김김김");
            var func = hello;
        func("피카츄");
        */
         
        // 함수를 매개변수에 담을 수 있다.
        function hello1(){
            console.log("hello!!!");
        }
        function hello2(){
            console.log("hello22222");
        }
        //매개변수를 함수로 실행하는 함수
      //중요
        function execute(func){
            func();
        }
        execute(hello1);
        execute(hello2);
    
    </script>
    
</body>
</html>




6) 리턴값으로 함수 사용하기
: 함수는 어떤 값이든 리턴가능. 즉, 함수를 리턴할 수도 있다.

 

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
   <script>  // 10-6 설명
    function getHello(){
        function hello(user){
            console.log(user + "님 방문을 환영합니다.");
        }
        return hello;  // 함수 이름을 리턴 
    }
    var result = getHello(); // 힘수를 리턴받아 변수에 저장
       result();
       result("홍길동");
    
    </script>
    
</body>
</html>

9. 배열 array
: 다양한 데이터 타입의 값 저장 가능

1) 배열 생성
#1. 배열 객체 생성
var 참조변수명 = new Array();

변수명[0] = 값;


#2. 배열 객체 생성 + 초기값
var 참조변수명 = new Array(값1, 값2, 값3,....);

  #3. *배열 리털로 생성
var 참조변수명 = []; // 빈 배열
var 참조변수명 = [값, 값2, .....];

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <script>
       //배열 #1
        var arr1 = new Array();
        arr1[0] = 10;
        arr1[1] = "abc";
        arr1[2] = true;
        
        console.log(arr1);
    

        //#2
        var arr2 = new Array(10, 'abcd', false);
        console.log(arr2);
       
        arr2[0]= 200;
        console.log(arr2); 
        
        //#3
       var arr3 = [];
        console.log(arr3);
 
    </script>
</body>
</html>

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
  <script>
    var arr = [100, "abc", true];
      
      arr[3] = -20;
      console.log(arr);
      
      arr[5] = 1000;   //arr[4] 에는 empty가 생김
      console.log(arr); //[100, 'abc', true, -20, empty, 1000]
      
      
      // 배열의 길이
      console.log(arr.length); // 6
        
      //데이터 배열 맨 뒤에 추가 : push()
      arr.push(2000);   
      console.log(arr);     //[100, 'abc', true, -20, empty, 1000, 2000]
      //데이터 배열 맨 앞에 추가 : unshift()
      arr.unshift(2000);
      console.log(arr);    //[2000, 100, 'abc', true, -20, empty, 1000, 2000]
      
      
      // 배열 마지막 데이터값 꺼내서 리턴하고 배열에서는 삭제 : pop()   
      console.log("pop() : " + arr.pop());    //pop() : 2000
      console.log(arr);                   //[2000, 100, 'abc', true, -20, empty, 1000]
      // 배열 앞 데이터값 꺼내서 리턴하고 배열에서는 삭제 : shift()
      console.log("shift() : " + arr.shift());   //shift() : 2000
      console.log(arr);         //[100, 'abc', true, -20, empty, 1000]
      
      // 연결문자 삽입 : join("연결문자")
      var res = arr.join("-")
      console.log(res);  //100-abc-true
      
      // 배열 결합 : concat(배열)
      
      // 베열잘라내기 : slice(startIndex, endIndex)
      res = arr.slice(0,2);
      console.log(res); //[100,'abc']
      
      
      var arr2 = ["bb", "BB", "aa", "AA", 7,2 ,"하늘소","아메라카노", true] 
      // 오름차순 정렬 : sort()
      res = arr2.sort();
      console.log(res);       //[2,7,"AA", "BB","aa","bb",true, "아메리카노", "하늘소]
      
      // 배열 역순 : reverse()
      res = res.reverse();
      console.log(res);       // ['하늘소', '아메라카노', true, 'bb', 'aa', 'BB', 'AA', 7, 2]
      
    </script>
    
</body>
</html>

7. 입력문 (잘안씀)
: 입력창을 통하여 사용자로부터 데이터를 입력받는 기능

변수=prompt("질문");
변수=prompt("질문", "default 답변")

입력받은 값은 모두 문자타입으로 받음

8. 제어문 
- 조건문 : if, switch
- 반복문 : while, do while, for
- 보조제어문 : continue, break

 

<!DOCTYPE html>  
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <script>
     //입력문  
     	var age = prompt("당신의 나이는?");
        console.log(age);
        //제어문 if 문
        var num = 0;
        if(num < 100 && num > 0){
            console.log(" 100보다 작다");
        
        }else {
            console.log("100보다 크거나 같다");
        }
       // switch
        var num2 = prompt("정수 입력하세요", 1);
        switch(num2){
            case "1" :
                console.log("1을 입력하셨습니다");
                break;
            case "2" :
                console.log("2를 입력하셨습니다");
                break;
            default:
                console.log("다른 숫자를 입력하셨습니다");
                //break;
        }
        
        
    </script>
</body>
</html>

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    
    
    <script>
        var i = 0; 
        while(i < 10){
            document.write("hello<br />");
            i++; 
        }
        
        var a = 0; 
        while(true){
            a++;
            document.write("X10 print");
            if(a == 10){
                break;
            }
        }
        document.write("<br />");
        
        i = 0; 
        do{
            i++; 
            document.write("asdf");
        
        }while(i < 5);
  
    </script>
</body>
</html>

[Javascript]

1. 자바스크립트
HTML : 브라우저에 표시할 내용 나열
CSS : HTML 요소에 디자인 접목
Javascript : 정적인 웹 문서에 동작을 부여(동적)

 @ 1) 객체 기반의 스크립트 프로그래밍 언어
웹브라우저 내에서 많이 사용, 다른 응용프로그램의 내장 객체에도 접근 가능한 기능있음.
웹 브라우저에는 javascript 엔진 (번역해서 실행시켜주는 역할)이 탑재되어 있다.
브라우저가 아닌 환경에서 실행시키고 싶으면 엔진을 설치해야함
(node검색 > 엔진 다운받아 설치 가능)


2. 기본사항

1) 작성 방법
- HTML 문서안에 <script> 태그안에 작성
- 확장자가 .js 파일에 js코드 작성하고 html문서에 연결.
<script src="js파일경로"></script>

2) 주석 
// 한줄 주석
/* 여러줄 주석 */


3. 변수
int num 10;   double num 10.123;
   var num = 10; var num = 10.123;

* ES6 버전부터 바뀐 : let, const


4. 데이터 타입
: 값의 종류들

1) 숫자형 Number
정수:  10진수  그냥쓰면됨
16진수 0x로 시작, 0~9 A~F (주로 색상값 나타낼때 사용)
실수: 소수점 있는수

2) 문자형 String
문자열 홑/겹 따옴표로 묶은 형태

3) 논리형 Boolean
true / false 두가지 경우의 값을 갖는 형태

4) undefined
: 변수를 선언만하고, 초기화하지 않는것 출력
함수 인자값 없이 호출되는 경우
존재하지 않는 속성을 접근한 경우

5. 연산자
1) 산술 : + _ * / %
2) 대입 : =
3) 복합대입 : += -= *= /= %=
4) 증감 : ++ -- (전위형, 후위형)
5) 비교 : < <= => >
== : 데이터의 타입 관계없이 같으면 true 10=="10" true
=== : 데이터의 타입도 같아야 true 10 === "10" false
!= : 데이터 타입 관계없이 같으면 false
!== : 데이터 타입도 일치해야 false
6) 논리 : || or  / && and  / !
7) 삼항 : var b = (5 < 4) ? 50 (참일때): 40; (거짓일때) 

<!-- js01.html --> 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    
    
    
    
    <script>
        // 자바스크립트 작성 영역 
        // #1. console.log() (-> 브라우저 개발자도구의 console탭에 출력)
        //console.log("hello!!!");
        // #2. alert() (-> 브라우저에 경고창으로 띄우기)
        //alert("안녕하세요");
        // #3. document.write()  (-> 브라우저 화면에 출력하기)
        document.write("<h1>hello js</h1>"); 
        
        var name = "홍길동"; 
        var age = 30; 
        var play = false;
        console.log(name);
        console.log(typeof name); // 해당 변수의 타입 리턴 
        console.log(typeof age);
        console.log(typeof play);
     
        var test;
        console.log(test);

        
    </script>
</body>
</html>

6. 형변환
: 데이터 타입을 변환 시키는 작업
# 자동형변환
1) 숫자 + 문자 => 문자
2) 불린 + 문자 => 문자
3) 불린 + 숫자 => 숫자 (true = 1, false = 0)

(*제일많이씀*) 숫자 -> 문자 : 10+"" -> "10"

# 강제형변환
1) 문자 -> 숫자
정수 : parseInt()
Number()
실수 : parseFloat()
Number()
2) 숫자 -> 문자
일반문자 : String()
16진수 : .toString(진수)
실수문자: .toFixed(소수점자리수)

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
   
   <script>
    //자동형변환
       var a = "30";
       var res = 1 + a + 10;  //13010로 나옴
       var res2 = a + 1 + 10; //30110
       console.log(res2); 
       
       res = 2 + true;
       console.log(res);
       //
    
       
       //강제 형변환
       //문자 -> 숫자
       var num = "123.456";   
       res3 = parseInt(num);   //정수로 변환  소수점 x
       console.log(res3);
       res4 = Number(num);      // 숫자로 변환 소수점 o/x
       console.log(res4);
       res5 = parseFloat(num); //실수로 변환
       console.log(res5);
       
       
       //숫자 -> 문자
       var num = 123.343
       res6 = String(num);
       console.log(res6);
       console.log(typeof res6);
    </script>
    
</body>
</html>

+ Recent posts