[TIL] 자바스크립트 기초

공부할 책 : Do it! 자바스크립트 + 제이쿼리 입문
자바스크립트 기초만 (제이쿼리 전까지)

1학년 1학기때 웹 프로그래밍을 배우고 한동안 웹프로그래밍 공부를 안한 것 같다.
여름방학때 React를 공부 찍먹해봤는디 어려웠다.. 더 기본을 갖추고 다시 공부하는게 좋을듯!
그런의미로 자바스크립트를 복습하려고 하는 글이다. HTML이랑 CSS는 이미 충분한거 같고...

이번 방학땐 열씨미 공부해서 알차게 보내는게 목표...!
자바스크립트를 배우고자 남기는 흔적글...
이미 알고 있거나 쉬운 내용은 패스!

다음 사진은 예제이다. 간단한 예제고 학교에서 이미 배운거지만 흔적남기는게 중요할 것 같아서..


쉬운건 넘어가자

자바스크립트 기초 문법

선언문

<script>
    자바스크립트 코드
</script>

주석 처리

자바스크립트 : '// 내용' 또는 '/* 내용 */' 
HTML : '<!-- 내용 -->'

내부 스크립트 외부 분리

예시 :
<script src="js/example.js"></script>

변수

변수 선언

var 변수명; 또는 var 변수명=값;

담을 수 있는 자료형 : 문자형, 숫자형, 논리형

논리형 데이터 : Boolean 메서드

var k = Boolean("hello") 	// true
var m = Boolean(0) 		// false

null & undefined 데이터

var s; 		//undefined
var t = hello;
t = null;

typeof

    <script>
        var num = 100;
        var str = '자바스크립트';

        document.write(typeof num, "<br>");
        document.write(typeof str);
    </script>

실행결과 :

연산자

var a = 10;
var b = "10";

a == b		// 숫자가 일치하면 자료형이 일치하지 않아도 true
a === b 	// 숫자가 일치해도 자료형이 일치하지 않으면 false

나머지 (--, ++, !, &&, ||) 는 쉬워서 생략..

제어문

C언어 배워서 눈감고도 풀듯.. 이것도 생략

예제 실습


객체

자바스크립트의 객체는 크게 내장객체, 브라우저 객체모델(BOM), 문서 객체모델(DOM) 로 나뉜다.

내장 객체

자바스크립트 엔진에 내장되어 있어 필요한 경우 생성해서 사용
String, Date, Array, Math 객체 등이 있다.

참조 변수(인스턴스 이름) = new 생성 함수()
예시 :
var tv = new Object();
var t = new Date();

Object 객체 예제

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>
        var tv = new Object();
        tv.color="white";
        tv.price=300000;
        tv.info=function(){
            document.write("tv 색상: "+this.color,"<br>");
            document.write("tv 가격: "+this.price,"<br>");
        };
        var car = {
            color: "black",
            price: 500000,
            info: function(){
                document.write("car 색상: "+this.color,"<br>");
                document.write("car 가격: "+this.price,"<br>");
            }
        };
        document.write("<h1>tv 객체 메서드 호출</h1>");
        tv.info();
        document.write("<h1>car 객체 메서드 호출</h1>");
        car.info();
    </script>
</head>
<body>
</body>
</html>

결과

Date 객체 예제

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>
        var today = new Date();
        document.write("<h1>오늘 날짜 정보</h1>");
        document.write("현재 월: "+today.getMonth()+"<br>");
        document.write("현재 일: "+today.getDate()+"<br>");
        document.write("현재 요일: "+today.getDate()+"<br>");

        var worldcup = new Date(2002,4,31);
        var theMonth = worldcup.getMonth(),
        theDate = worldcup.getDate(),
        theDay = worldcup.getDay();

        document.write("<h1>월드컵 날짜 정보</h1>");
        document.write("2002월드컵 몇 월: "+theMonth,"<br>");
        document.write("2002월드컵 몇 일: "+theDate,"<br>");
        document.write("2002월드컵 무슨 요일: "+theDay,"<br>");
    </script>
</head>
<body>
</body>
</html>

결과 :

Date 객체 예제 :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>
        var num = 2.1234;

        var maxNum = Math.max(10,5,8,30),
        minNum = Math.min(10,5,8,30),
        roundNum = Math.round(num),
        floorNum = Math.round(num),
        ceilNum = Math.ceil(num),
        rndNum = Math.random(),
        piNum = Math.PI;

        document.write(maxNum,"<br>");
        document.write(minNum,"<br>");
        document.write(roundNum,"<br>");
        document.write(floorNum,"<br>");
        document.write(ceilNum,"<br>");
        document.write(rndNum,"<br>");
        document.write(piNum,"<br>");
    </script>
</head>
<body>
</body>
</html>

결과 :

Array 객체

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>
        var arr_1 = ["사당","교대","방배","강남"];
        var arr_2 = ["신사","압구정","옥수"];

        console.log(arr_1.join("-"));
        console.log(arr_1.concat(arr_2));
        console.log(arr_1.slice(1,3));
        console.log(arr_1.sort());
        console.log(arr_2.reverse());
        arr_1.splice(2,1,"서초","역삼")     //2번째 인덱스부터 1개의 데이터를 삭제하고 서초,역삼 을 넣는다
        console.log(arr_1);
        console.log(arr_1.pop());        //가장 마지막 인덱스
        console.log(arr_1.shift());      //가장 앞 인덱스
        arr_1.push("ㅁㄴㅇㄹ"); //arr_1 맨 마지막 인덱스에 밀어 넣는다.
        console.log(arr_1); 
        arr_1.unshift("ㄹㅇㄴㅁ"); //arr_1 가장 앞 인덱스에 밀어 넣는다.
        console.log(arr_1);
    </script>
</head>
<body>
</body>
</html>

결과 :

String 객체 예제

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>
        var t = "Hello Thank you good luck to you";

        document.write(t.charAt(16),"<br>");
        document.write(t.indexOf("you"),"<br>");
        document.write(t.indexOf("you",16),"<br>");
        document.write(t.lastIndexOf("you"),"<br>");
        document.write(t.lastIndexOf("you",25),"<br>");
        document.write(t.match("you"),"<br>");
        document.write(t.search("you"),"<br>");
        document.write(t.substr(21,4),"<br>"); // 인덱스 21부터 4글자
        document.write(t.substring(6,12),"<br>"); // 인덱스 6부터 인덱스 12까지
        document.write(t.replace("you","me"),"<br>");
        document.write(t.toLowerCase(),"<br>");
        document.write(t.toUpperCase(),"<br><br>");

        var s=t.split(" ");
        document.write(s[0],"<br>");
        document.write(s[4],"<br>");
    </script>
</head>
<body>
</body>
</html>

결과 :


브라우저 객체 모델 (BOM)

브라우저에 계층 구조로 내장되어 있는 객체
window, screen, location, history, navigator 객체 등이 있다.
브라우저(window)는 document와 loction 객체의 상위 객체이다.

window 객체 메서드 종류

open, alert, prompt, confirm, moveTo, resizeTo, setInterval, setTimeout

open() 메서드

window.open("URL","새 창 이름","새 창 옵션")

새 창 옵션 종류 :
width - 새 창의 너비 설정
height - 새 창의 높이 설정
left - 새 창의 x축 위치 설정
top - 새 창의 y축 위치 설정
scrollbars - 새 창의 스크롤바 숨김/노출 설정 (숨김 : scrollbars=no)
location - 새 창의 url 주소 입력영역 숨김/노출 설정 (숨김 : location=no)
status - 새 창의 상태 표시줄 숨김/노출
toolbars - 새 창의 도구 상자 영역 숨김/노출

예제 :

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset = "UTF-8">
<title> window 객체  </title>
<script>
	window.open("winpopup.html","pop1","width=300,height=400,left=900,top=50");
</script>
<style>
	*{margin: 0;padding: 0;}
</style>
</head>
<body>
<p>
	<img src="images/window_object_1.jpg" usemap="#intro"
	alt="신간 책 소개" />
	<map name="intro" id="intro">
			<area shape="rect" coords="230,368,280,390" href="#" alt="창 닫기" onclick="window.close();"/>
	</map>
</p>  
</body>
</html>

alert() 메서드

확인 버튼만 나타나는 창
예제 :

alert("경고 메세지")

prompt() 메서드

질의응답 창
예제 :

var aa = prompt("질의 내용","기본 답변"

confirm() 메서드

확인/취소 버튼 나타내는 창
예제 :

confirm("질의 내용")

setInterval() / clearInterval() 메서드

setInterval() : 코드를 일정 시간 간격으로 반복 실행
var 참조변수 = setInterval(function() {코드}, 시간간격(ms));
var 참조변수 = setInterval("코드", 시간간격(ms))

clearInterval() : setInterval()메서드 취소

예제 :

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset = "UTF-8">
<title> window 객체 </title>
<script>
	var addNum = 0;
	var subNum = 1000;

    var auto_1 = setInterval(function(){
        addNum++;
        console.log("addNum: "+addNum);
    },3000);

    var auto_2 = setInterval(function(){
        subNum--;
        console.log("subNum: "+subNum);
    },3000);
</script>
</head>
<body>
    <h1>일정 시간 간격으로 값 증감시키기</h1>
    <p> 콘솔 패널을 열어 확인하세요.</p>
   <button onclick="clearInterval(auto_1)">증가 정지</button>
   <button onclick="clearInterval(auto_2)">감소 정지</button>
</body>
</html>

setTimeout() / clearTimeout() 메서드

setTimeout() : 일정 시간이 지나면 코드 실행 후 종료
clearTimeout() : setTimeout 메서드 제거

var 참조 변수 = setTimeout(function() {자바스크립트 코드}, 시간간격)
clearTimeout(참조변수)

screen 객체

사용자 모니터 정보(속성) 제공하는 객체

screen.width 화면의 너비값 반환
screen.height 화면의 높이값 반환
screen.availWidth 작업표시줄 제외 화면너비값
screen.availHeight 작업표시줄 제외 화면높이값

location 객체

사용자 브라우저와 관련된 속성과 메서드 제공

location.href 주소 영역의 URL 반환

history 객체

사용자가 방문한 사이트의 기록을 남기고 이전 방문 사이트와 다음 방문 사이트로 다시 돌아갈 수 있는 속성과 메서드 제공

history.back() 이전 방문 사이트로
history.forward() 다음 방문 사이트로
history.go(이동숫자) 이동숫자에 -2 입력시 2단계 이전 방문사이트로
history.length 방문기록에 저장된 목록 개수 반환

navigator 객체

현재 방문자가 사용하는 브라우저 정보와 운영체제 정보 제공

예제 :

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset = "UTF-8">
<title> 운영체제 및 스크린 정보 </title>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
<script>
    var info = navigator.userAgent.toLowerCase();
    var osImg = null;

    if(info.indexOf('windows')>=0){
        osImg="windows.png";
    }else if(info.indexOf('macintosh')>=0){
        osImg="macintosh.png";
    }else if(info.indexOf('iphone')>=0){
        osImg="iphone.png";
    }else if(info.indexOf('android')>=0){
        osImg="android.png";
    }

    document.write("<img src=\"images/"+osImg+"\">","<br>")
    var scr = screen;
    var sc_w = scr.width;
    var sc_h = scr.height;
    
    document.write("해상도너비 : " + sc_w);
    document.write("해상도높이 : " + sc_h); 
</script>
</head>
<body>
</body>
</html>

결과 :

문서 객체 모델 (DOM)

문서 객체 모델은 HTML 구조를 말한다.
최상위 객체로 <html> 이 있으며 하위 객체로는 <head><body>가 있다.


함수

function 함수명(){
    자바스크립트 코드;
}

예제 :

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset = "UTF-8">
<title> 함수 </title>
<script>
	var rightId = "korea";
	var rightPw = "1234";
	function login(id,pw){
		if(id==rightId){
			if(pw==rightPw){
				document.write(id+"님 방문을 환영합니다.");
			}else{
				alert("잘못된 비밀번호입니다.");
			}
		}else{
			alert("존재하지 않는 아이디입니다.");
		}
	}
	var userId = prompt("아이디입력","");
	var userPw = prompt("비밀번호입력","");

	login(userId,userPw);
</script>
</head>
<body>
</body>
</html>

결과 :

매개변수 없이 함수에 전달된 값 받아오기

function 함수명(){
    arguments; // arguments[0] = 데이터1, arguments[1] = 데이터2 ...
}

함수명(데이터1,데이터2,데이터3);

스코프 (전역변수 지역변수)

패스

객체 생성자 함수

예제 :

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset = "UTF-8">
<title> 함수 </title>
<script>
    function CheckWeight(name,height,weight){
        this.userName=name;
        this.userHeight=height;
        this.userWeight=weight;
        this.minWeight;
        this.maxWeight;
        this.getinfo=function(){
            var str=""
            str+="이름: "+this.userName+",";
            str+="키: "+this.userHeight+",";
            str+="몸무게: "+this.userWeight+"<br>";
            return str;
        }
        this.getResult=function(){
            this.minWeight=(this.userHeight-100)*0.9-5;
            this.maxWeight=(this.userHeight-100)*0.9+5;
            if(this.userWeight>=this.minWeigth && this.userWeight<=this.maxWeight){
                return "정상 몸무게입니다.";
            }else if (this.userWeight<this.minWeight){
                return "정상 몸무게보다 미달입니다.";
            }else {
                return "정상 몸무게보다 초과입니다.";
            }
        }
    }
    var jang = new CheckWeight("장보라",168,62);
    var park = new CheckWeight("박달재",180,88);
    console.log(jang);
    console.log(park);

    document.write(jang.getinfo());
    document.write(jang.getResult());
</script>
</head>
<body>
</body>
</html>


단 이방법은 함수를 여러 개 등록해서 메모리 공간을 많이 차지해 메모리를 낭비하게 된다.
이럴 때는 객체 생성자 함수에 프로토타입을 사용하여 함수를 등록하면 메모리 낭비를 줄일 수 있다.

객체 생성자 함수 (프로토타입)

프로토타입의 사전적 의미는 '원형' 이다.
프로토타입을 사용하여 등록한 함수는 원형에서 생성된 객체를 공유할 수 있다.

예제 :

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset = "UTF-8">
<title> 함수 </title>
<script>
    function CheckWeight(name,height,weight){
        this.userName = name;
        this.userHeight=height;
        this.userWeight=weight;
        this.minWeight;
        this.maxWeight;
    }
    CheckWeight.prototype.getinfo = function(){
        var str=""
        str += "이름: "+this.userName+", ";
        str += "키: "+this.userHeight+", ";
        str += "몸무게: "+this.userWeight+"<br>";
        return str;
    }
    CheckWeight.prototype.getResult = function(){
        this.minWeight = (this.userHeight-100)*0.9-5;
        this.maxWeight = (this.userHeight-100)*0.9+5;
        if(this.userWeight>=this.maxWeight && this.userWeight<=this.maxWeight){
            return "정상 몸무게입니다.";
        }else if(this.userWeight<this.minWeight){
            return "정상 몸무게보다 미달입니다.";
        }else{
            return "정상 몸무게보다 초과입니다.";
        }
    }
    var jang = new CheckWeight("장보라",168,62);
    var park = new CheckWeight("박달재",180,88);
    console.log(jang);
    console.log(park);

    document.write(jang.getInfo());
    document.write(jang.getResult(), "<br>");

    document.write(jang.getResult === park.getResult)
</script>
</head>
<body>
</body>
</html>

내장 함수

encodeURl() 문자를 유니코드값으로 인코딩
encodeURlComponent() 문자를 유니코드값으로 인코딩 (영문,숫자 제외)
decodeURl() 유니코드값 디코딩해 다시 문자화
parseInt() 문자열 데이터 → 정수형 데이터
parseFloat() 문자열 데이터 → 실수형 데이터
String('숫자') 문자형 데이터로 반환
Number('문자') 숫자형 데이터로 반환
Boolean() 논리형 데이터로 반환
isNaN() 숫자가 아닌 문자가 포함되어 있으면 true 반환
eval() 문자형 데이터를 따옴표가 없는 자바스크립트 코드로 처리


후기

다 학교에서 배운거라 공부한 의미가 없는 것 같다. 그것도 자바스크립트 기초..
심화내용이 없어서 아쉽다..ㅠ
구글링하면 책보다 더 많이 배울 것 같은디..
그래도 앞으로 배울 제이쿼리를 배우려면 자바스크립트 기초를 알아야 하니 복습삼아 흔적글 끄적끄적..

좋은 웹페이지 즐겨찾기