JavaScript 생활코딩 강의 정리

Eunsuh Kim·2022년 9월 24일
0

정의

JavaScript

  • HTML과 CSS로 만들어진 웹페이지를 동적으로 (사람들과 상호작용할 수 있도록) 변경해주는 언어
  • e.g., 야간 모드: 사용자의 조작에 반응하여 사용자가 버튼을 클릭할 경우 JS 코드의 body 태그, style 속성이 웹브라우저의 디자인을 바꿔줌.

HTML과 JS

  • HTML, JS = 컴퓨터 언어
  • JS = 컴퓨터 언어인 동시에 컴퓨터 프로그래밍 언어 (HTML은 컴퓨터 프로그래밍 언어 X)
  • JS는 사용자와 상호작용하기 위해 고안된 언어이고, 그러기 위해서는 시간 순서대로 기능들이 실현되어야 함 -> '프로그래밍'이라는 특성 有

<script> 태그

  • 웹브라우저는 <script></script> 태그 안쪽의 태그를 JS로 해석
<script>
	document.write(1+1)
</script>
  • document.write(): JavaScript 출력문
  • 위의 코드는 웹브라우저에서 2로 출력(JS가 동적이기 때문)
  • cf. HTML로 1+1 출력 시 그대로 출력

이벤트 (event)

  • 웹 브라우저가 알려주는 HTML 요소에 대한 사건의 발생
  • 웹 페이지에 사용된 JavaScript는 이벤트에 반응하여 특정 동작을 수행할 수 있음 (사용자와 상호작용하는 데 핵심적 역할)

이벤트의 종류

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
    <input type="button" value="hi" onclick="alert('hi')">
    <input type="text" onchange="alert('changed')">
    <input type="text" onkeydown="alert('key down!')">
</body>
</html>
onclick: 사용자가 HTML의 요소를 클릭했을 때
  • hi 버튼을 만들고 버튼을 누르면 'hi' 경고창이 뜨게 함
onchange: HTML의 요소가 바뀌었을 때 (텍스트 입력칸 변경 등)
  • text input 창에 값을 입력 후 마우스포인트를 밖으로 빼면 onchange 이벤트 실행, 'changed' 경고창이 뜸
(3) onkeydown: 사용자가 키보드 키를 눌렀을 때
  • text input 창에 텍스트 키를 입력 시 onkeydown 이벤트 실행, 'key down' 경고창이 뜸

콘솔

  • 개발자 도구 > Console 탭
  • 콘솔을 사용하면 파일을 따로 만들지 않아도 JS를 즉각적으로 실행 가능

데이터 타입

JavaScript 언어의 타입은 원시 값객체로 나뉨

원시 값 (primitives)

  • Boolean
  • Null
  • Undefined
  • Number
  • BigInt
  • String
  • Symbol

객체 (object)

(하단 참고)

숫자와 문자열

숫자

  • 산술연산자: 피연산자에 대해 사칙연산을 포함한 각종 산술연산을 수행하는 연산자로 이항연산자단항연산자로 구분
  • 이항연산자: 2개의 자료를 대상으로 산술적인 처리를 수행하는 연산자로, +,-,*,/ 등을 포함
  • 숫자는 이항연산자로 계산될 수 있음

문자열

  • "" 또는 '' 안에 입력됨
Properties
  • str.length: str의 글자수 반환
Methods
  • str.toUpperCase(): 대문자로 반환
  • str.indexOf(searchValue[, fromIndex]): index number 반환 (0부터 시작 / 괄호 안이 str일 경우 맨 앞 글자의 index number)
  • str.trim(): str 앞뒤 공백 없앰

변수와 대입연산자

x=1;
  • x는 변수, =는 대입연산자
1=2;
  • 불가능 (숫자 1은 값이 바뀔 수 있는 변수가 아니라 상수이기 때문)
var name = 'leezche';
alert("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut dignissim massa quis lacus "+name+" tempus malesuada. Nulla condimentum magna nec semper sodales. Suspendisse aliquam at nibh eget lacinia. Proin ultrices lacus dui, sit amet elementum sapien luctus ut. Vestibulum ante ipsum primis in faucibus orci "+name+" luctus et ultrices posuere cubilia curae; Etiam bibendum, velit vel auctor faucibus, purus ligula auctor nisi, vitae venenatis nibh urna nec felis. Donec ex nisi, dictum in blandit vel, posuere in mi. Nullam vel placerat erat, eget porta diam. Vestibulum hendrerit lorem ac lacus "+name+" ornare, quis convallis justo efficitur.")
  • 변수 할당 시 앞에 var 키워드를 써야 함

CSS 기초

웹브라우저 제어

  • night, day 버튼 눌렀을 때 화면 색이 바뀌게 하려면 <body> 태그의 style 속성에 CSS 값 넣어줘야 함
    이것을 위해
    (1) CSS, style 속성의 문법 및
    (2) 자바스크립트를 이용해서 제어하고자 하는 태그를 선택하는 방법
    을 파악 필요

style 속성

  • CSS 언어로 웹페이지를 디자인하고 싶을 때
<h2 style="">JavaScript</h2>

태그 안에 style 속성을 쓰고 그 안에 CSS 사용

style 태그

이름기능
<div>CSS나 JS를 통해 어떤 정보를 제어하고 싶을 때 그것을 감싸주는 태그
- 웹페이지 전체를 쓰는 태그여서 줄바꿈 가능
<span><div> 태그와 동일한 기능이지만 줄바꿈이 안됨
<style><script> 태그처럼 <style> 태그 안의 텍스트가 CSS라는 것을 웹브라우저에게 알려주는 역할을 하는 구분자
  • 여러 개의 JavaScript라는 단어 모두 빨간색 bold로 하고 싶다면?
    -> e.g., <span> 태그 안의 class 속성 값이 js인 태그에 대한 것이면, <style> 태그 안에 .js{ } 입력하고 그 안에 CSS 입력

선택자

  • 여러 개의 JavaScript라는 단어 중 맨 앞의 것만 초록색으로 하고 싶다면? -> <span> 태그 안의 id 속성 값이 first인 태그에 대한 것이면, <style> 태그 안에 #first{ } 입력하고 그 안에 CSS 입력
<span id="first" class="js">JavaScript</span>

Q. 위의 <span> 태그는 idclass의 영향 둘다 받는데 왜 초록색으로 나타날까?

  • idclass의 의미 차이를 봐야 함.
  • id = 어떤 한 가지 대상을 식별
  • class = 어떤 대상들을 그룹핑
  • 만약 id=”first”가 한 번 등장했다면 그 코드 안에서 id=”first”는 더 이상 쓰면 안됨
  • classid보다 포괄적; class 지정하고 id는 예외적으로 사용
  • 즉, 같이 쓰이면 idclass보다 우선순위

Q. 웹페이지의 모든 <span> 태그에 대해 파란색을 하고 싶다
-> <style> 태그 안에 span 입력하고 그 안에 CSS 입력 (span 앞에 아무것도 안 붙임)

  • id, class가 영향 주는 <span> 태그의 경우 id가 더 우선순위
  • id > class > span 순으로 우선순위

제어할 태그 선택하기

 <h1><a href="index.html">WEB</a></h1>
    <input type="button" value="night" onclick="
    document.querySelector('body').style.backgroundColor='black';
    document.querySelector('body').style.color='white';    
    ">
    <input type="button" value="day" onclick="
    document.querySelector('body').style.backgroundColor='white';
    document.querySelector('body').style.color='black';    
    ">

(1) 어떻게 버튼을 누르면 body 태그 전체를 선택?

var el = document.querySelector(".myclass");

-> 웹페이지에 있는 모든 태그 중 class명이 myclass인 태그를 선택하는 선택자
이 경우 body 태그를 직접 선택할 것이기 때문에 document.querySelector(‘body’)

(2) 어떻게 선택한 body 태그 전체 대상으로 style 속성을 어떻게 JS로 넣을 수 있나?
https://www.w3schools.com/jsref/dom_obj_style.asp
https://www.w3schools.com/jsref/prop_style_backgroundcolor.asp

위의 2개 자료를 참고해서 document.querySelector(‘body’).style.backgroundColor=’black’;
(CSS에서는 background-color인데 JS에서는 backgroundColor임을 유의)
document.querySelector(‘body’).style.color=’white’;
(그냥 color는 텍스트 색깔)

여기까지 night mode 완성

똑같이 복붙해서 색깔 바꿔주면 day mode 완성

문법

조건문 (if문)

  • 비교연산자: 피연산자를 서로 비교하고, 비교 결과가 참인지 거짓인지에 따라 Boolean(True, False)를 반환, ===, <, > 등이 있음
  • <는 태그와 위치 겹칠 경우 &lt;와 같이 쓸 수 있음

리팩토링: 중복의 제거

<input id="night_day2" type="button" value="night" onclick="
    if(document.querySelector('#night_day2').value === 'night'){
        document.querySelector('body').style.backgroundColor='black';
        document.querySelector('body').style.color='white';
        document.querySelector('#night_day2').value = 'day'
    } else {
        document.querySelector('body').style.backgroundColor='white';
        document.querySelector('body').style.color='black';
        document.querySelector('#night_day2').value = 'night'
    }
    ">

여기에서
(1) document.querySelector('#night_day2')onclick 이벤트가 속해 있는 자기 자신을 가리킴 -> this로 바꿈

  • 코드가 간결해짐
  • 같은 기능의 버튼을 여러 번 만들 때, this를 사용하여 리팩토링하면 계속 id 바꿀 필요 X

(2) document.querySelector('body')가 중복 ->
var target = document.querySelector('body')으로 변수 설정한 후 밑의 중복되는 부분들을 변수로 대체

  • 중복 줄어들음
  • 변수 안의 값이 바뀔 경우 var 만 수정해주면 모든 코드가 변경

변경 후:

<input id="night_day" type="button" value="night" onclick="
    var target = document.querySelector('body');
    if(this.value === 'night'){
        target.style.backgroundColor='black';
        target.style.color='white';
        this.value = 'day'
    } else {
        target.style.backgroundColor='white';
        target.style.color='black';
        this.value = 'night'
    }
    ">

배열 (array)

array의 형식

get
  • index number은 0부터 시작
add

count

  • .length
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
    <h1>Array</h1>
    <h2>Syntax</h2>
    <script>
        var coworkers = ["egoing","leezche"];
    </script>

    <h2>get</h2>
    <script>
        document.write(coworkers[0]);
        document.write(coworkers[1]);
    </script>

    <h2>add</h2>
    <script>
        coworkers.push('duru');
        coworkers.push('taeho');
    </script>

    <h2>count</h2>
    <script>
        document.write(coworkers.length);
    </script>
</body>
</html>

반복문

  • 프로그램 실행 순서의 흐름을 제어 (조건문과 함께)
  • 반복문에서는 반복문이 언제 종료되는지 정하는 것 필요
  • 코드를 n번 반복하고 싶으면, 코드가 몇 번 실행되었는지 i라는 변수에 저장하고 = i + 1 기존 코드 맨 밑에 추가, while(i < n+1) 반복문의 조건으로 설정

형식

while(){ }

  • while 뒤 소괄호 안에는 Boolean 데이터 타입(True/False)가 들어감
  • JS가 소괄호 안이 True인지 확인 -> True일 경우 중괄호 안 처음부터 끝까지 실행 -> 다시 위로 올라와서 True인지 확인 -> True이면 앞의 과정 반복, False이면 while문 밖의 코드 실행

배열과 반복문의 활용

  • 배열의 원소: element
  • 코드를 바꾼다고 로직이 바뀌는 것을 최소화
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
    <h1>Loop & Array </h1>
    <script>
        var coworkers = ['egoing','leezche','duru','taeho', 'graphittie'];
    </script>
    <h2>Co workers</h2>
    <ul>
        <script>
            var i = 0;
            while(i < coworkers.length){
                document.write('<li><a href="http://a.com/'+coworkers[i]+'">'+coworkers[i]+'</a></li>');
                i = i + 1;
            }
        </script>
    </ul>
</body>
</html>

콘솔 창에서

  • document.querySelector(‘a’): <a> 태그에 해당하는 첫번째 태그만 가져옴.
  • document.querySelectorAll(‘a’): <a> 태그에 해당하는 모든 태그를 배열(node list)로 가져옴
var alist = document.querySelectorAll(‘a’);
console.log(alist[0]); // 또는 (alist.length)

-> 괄호 안의 결과가 콘솔 창에 출력

반복문을 이용, alist에 있는 태그를 하나하나 꺼내서 그것의 style 속성을 지정하려면? 아래와 같이 콘솔 창에 입력

var alist = document.querySelectorAll('a');
var i = 0;
while(i < alist.length){
    console.log(alist[i]);
    alist[i].style.color = 'powderblue';
    i = i + 1;
}

-> 태그를 화면에 출력할 수 있게 됨
(위쪽 화살표 키 누르면 위에 친 코드가 다시 나타남)

<!doctype html>
<html>
<head>
    <title>WEB1 - JavaScript</title>
    <meta charset="utf-8">
</head>
<body>
    <h1><a href="index.html">WEB</a></h1>
    <input id="night_day" type="button" value="night" onclick="
    var target = document.querySelector('body');
    if(this.value === 'night'){
        target.style.backgroundColor='black';
        target.style.color='white';
        this.value = 'day'

        var alist = document.querySelectorAll('a');
        var i = 0;
        while(i < alist.length){
            alist[i].style.color = 'powderblue';
            i = i + 1;
        }

    } else {
        target.style.backgroundColor='white';
        target.style.color='black';
        this.value = 'night'

        var alist = document.querySelectorAll('a');
        var i = 0;
        while(i < alist.length){
            alist[i].style.color = 'blue';
            i = i + 1;
        }

    }
    ">
    <ol>
        <li><a href="1.html">HTML</a></li>
        <li><a href="2.html">CSS</a></li>
        <li><a href="3.html">JavaScript</a></li>
    </ol>
    <h2>JavaScript</h2>
    <p>
        JavaScript (/ˈdʒɑːvəskrɪpt/), often abbreviated JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, often incorporating third-party libraries. All major web browsers have a dedicated JavaScript engine to execute the code on users' devices.
    </p>
    <input id="night_day2" type="button" value="night" onclick="
    if(this.value === 'night'){
        document.querySelector('body').style.backgroundColor='black';
        document.querySelector('body').style.color='white';
        this.value = 'day'
    } else {
        document.querySelector('body').style.backgroundColor='white';
        document.querySelector('body').style.color='black';
        this.value = 'night'
    }
    ">
</body>
</html>

함수

  • function 키워드 붙여서 만듦.
function nightDayHandler(){
}
  • 원래 함수를 nightDayHandler(this);로 대체하면 기존의 것보다 훨씬 더 효율적.
    이유: (1) 유지보수가 편함, (2) 웹페이지 크기가 작아짐, (3) 동일한 함수 사용한 부분은 동일한 로직이라는 점을 확신 가능

함수의 기본적인 문법

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
    <h1>Function</h1>
    <h2>Basics</h2>
    <ul>
        <script>
            function two(){
                document.write('<li>2-1</li>');
                document.write('<li>2-2</li>');
            }
            document.write('<li>1</li>');
            two();
            document.write('<li>3</li>');
            two();
        </script>
    </ul>
    <h2>Parameter & Argument</h2>
    <h2>Return</h2>
</body>
</html>

매개변수와 인자 (입력과 관련된 값들)

  • 매개변수 (parameter): 인자를 받아서 함수 안으로 매개해 주는 변수
    sum(left, right)에서 left, right이 파라미터
  • 인자 (argument): 함수로 전달하는 값
    sum(2,3)에서 2,3이 인자

리턴 (출력과 관련된 값들)

<script>
	function sum2(left, right){
    	return left+right;
    }
    document.write(sum(2,3)+'<br>');
    document.write('<div style="color:red">+sum2(2,3)+'</div>');
    document.write('<div style="font-size:3rem;">+sum2(2,3)+'</div>');
  • 계산 기능만을 sum2 함수가 구현함으로써 return에서 원자화된 기능을 다양한 맥락/용도에서 활용할 수 있는 자유도가 생김

활용

객체 (object)

  • 객체: 서로 연관된 함수와 변수를 그룹핑해서 정리정돈하기 위한 수납상자

객체 만들기 전 과정

(1) 중복된 코드 함수로 독립시키기

  • setColor 함수 정의 (링크 태그 색깔 변경) -> color 값을 매개변수로 세팅 -> 코드 내용 복붙
function setColor(color){
	var alist = document.querySelectorAll('a');
    var i = 0;
    while(i < alist.length){
    	alist[i].style.color = color;
        i = i + 1;
    }
}

(2) 함수를 통해 로직에 이름 부여

  • <body> 태그 의 폰트 컬러 바꾸는 함수 정의
function BodySetColor(color){
	document.querySelector('body').style.color = color;
}
  • 이미 정의된 함수의 경우 중복 사용되면 앞의 것이 덮어쓰기되어 삭제

  • 이 상황에서 <Body>라는 객체를 만들어서, 정리정돈하는 '폴더'와 같은 도구로 사용

객체 쓰기와 읽기

  • 배열은 대괄호, 객체는 중괄호
  • coworkers.programmer에서 .은 object access operator
  • 이미 객체가 만들어진 후 정보 추가하고 싶다면? -> 하단 코드 참고
  • key 이름에는 공백을 넣을 수 없음, [“ “]로 assign하고 가져와야 함

객체와 반복문

  • for(var key in coworkers){}: coworkers라는 변수가 가리키는 객체에 있는 key 값(programmer, designer 등)들을 가져와서, 중괄호의 코드를 실행해주는 반복문
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
    <h1>Object</h1>
    <h2>Create</h2>
    <script>
        var coworkers = {
            "programmer":"egoing",
            "designer":"leezche"
        };
        document.write("programmer : "+coworkers.programmer+"<br>");
        document.write("designer : "+coworkers.designer+"<br>");
        coworkers.bookkeeper = "duru"; // 정보 추가
        document.write("bookkeeper : "+coworkers.bookkeeper+"<br>");
        coworkers["data scientist"] = "taeho";
        document.write("data scientist : "+coworkers["data scientist"]+"<br>");
    </script>
    <h2>Iterate</h2>
    <script>
        for(var key in coworkers){
            document.write(key+' : '+coworkers[key]+'<br>');
        }
    </script>
    
</body>
</html>

객체: 프로퍼티와 메소드

  • 프로퍼티 (property): 객체에 소속된 변수
  • 메소드 (method): 프로퍼티 값이 함수일 경우, 일반 함수와 구분하기 위해 메소드라 부름. 즉 메소드는 객체에 제한되어 있는 함수 (showAll)

("programmer":"egoing")

  • 메소드 추가하는 방법: 함수 정의할 때 coworkers가 박혀 있는데, 이것을 고치기 위해 showAll 함수 안에서 함수가 소속되어 있는 객체를 가리키는 약속된 기호인 this로 function 정의 시의 coworkers를 대체하면 됨
    -> 웹페이지에서 showAll 함수 자체도 표시되는데, 이것은 나중에 if문 사용해서 제거 가능
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
    <h1>Object</h1>
    <h2>Create</h2>
    <script>
        var coworkers = {
            "programmer":"egoing",
            "designer":"leezche"
        };
        document.write("programmer : "+coworkers.programmer+"<br>");
        document.write("designer : "+coworkers.designer+"<br>");
        coworkers.bookkeeper = "duru"; // 정보 추가
        document.write("bookkeeper : "+coworkers.bookkeeper+"<br>");
        coworkers["data scientist"] = "taeho";
        document.write("data scientist : "+coworkers["data scientist"]+"<br>");
    </script>
    <h2>Iterate</h2>
    <script>
        for(var key in coworkers){
            document.write(key+' : '+coworkers[key]+'<br>');
        }
    </script>
    <h2>Property & Method</h2>
    <script>
        coworkers.showAll = function(){
            for(var key in this){
            document.write(key+' : '+this[key]+'<br>');
            }
        }
        coworkers.showAll();
    </script>
</body>
</html>

객체의 활용

  • 웹페이지의 Body에 대한 함수들을 정돈하려면?
  1. Body라는 객체 생성
  2. 객체의 property로 setColor를 지정하고 function 정의해줌
  3. 객체의 property와 property를 구분할 때 콤마 필요
var Body = {
	setColor:function (color){
    	document.querySelector('body').style.color = color;
    }
    setBackgroundColor:function (color){
    	document.querySelector('body').style.backgroundColor = color;
    }
}

파일로 쪼개서 정리정돈하기

  • 웹페이지가 1억 개라면 어떻게 수정 및 배포? 파일로 쪼개기
  • 공통된 부분들을 <script> 태그 제외하고 code.js에 복붙
  • 그 후 원래 파일에서 <script> 태그 안의 부분(복붙한 부분) 제외하고
    <script src="colors.js"></script>

이렇게 만들어주면 똑같은 출력이지만 완전히 다른 구조

  • 웹페이지 > 검사 > Network -> 웹페이지 화면에 표시하기 위해 로딩된 파일들이 보이는데 colors.js가 다운로드되어 있는 것 확인 가능
  • colors.js를 수정하면 그것을 포함한 모든 웹페이지에 자동으로 반영 -> 유지보수 편리, 로직 같음을 알 수 있음, 가독성 높아짐, 서버 입장에서는 비용 절감, 사용자 입장에서 트래픽 절감, 빠른 웹페이지 로딩 속도

참고

생활코딩 WEB2-JavaScript
이벤트의 개념
[생활코딩] JavaScript 기본문법 정리 (숫자와 문자, 변수, 주석, 줄바꿈과 여백, 비교)
제4장 연산자(operator)(산술 연산자, 관계 연산자)
객체와 프로퍼티,메소드
5.10 Object 객체

profile
안녕하세요!

0개의 댓글