JavaScript 기초 정리 by STUDIOMEAL

 
  • 출처: 구름EDU, STUDIOMEAL
HTML 파일 템플릿
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>자바스크립트 기초</title> <style> body { font-size: 3rem; } h1 { background: #fff000 } </style> </head> <body> </body> </html>
차례

JavaScript 시작하기

  • 스크립트의 위치
    • HTML파일 속
      • <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>자바스크립트 기초</title> <style> body { font-size: 3rem; } </stye> <script> document.write(111); </script> </head> <body> </body> </html>
    • 외부 파일
      • script.js
        document.write('외부 js 파일에서 출력');
        <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>자바스크립트 기초</title> <style> body { font-size: 3rem; } </stye> <script src="js/script.js"></script> </head> <body> </body> </html>
         
  • 경고창 띄우기
    • alert("반가워!");
  • 콘솔에 출력하기
    • console.log(111)
  • 주석
    • <html> <!-- 인사 메시지 영역 --> </html>
      // 한 줄 주석 /* 여러 줄 주석 */
 
  • 스크립트를 넣는 위치
    • 처음에는 <head> ... </head> 에 넣었지만
    • 요즘에는 <body> ... </body>의 마지막 부분에 넣는다
    • → 랜더링 속도를 높여주기 위해서. 빠른 척~
    • → 문서의 내용이 구성된 상태에서만 script 에서 문서의 내용을 알 수 있음
    •  

변수

  • ECMAScript의 버전에 따라서 다르기는 하지만 기본은....
var a = 100 a = 'ㅋㅋㅋ' console.log(a)
  • 이름 짓는 방법
    • 영어 뿐만 아니라, 한글, 일본어, 한자 다 쓸 수 있음
    • var 자바스크립트 = 20000; console.log(자바스크립트);
    • 일할 때는 영어로...
    • 개인 프로젝트에서는 가끔은 한글?
 

기본 데이터 형식 (자료형)

  • 숫자
  • 문자열
    • 'ㅋㅋㅋ'
    • "ㅋㅋㅋ"
    • var message = '"엄마가 그런 짓 하면 안 돼!"라고 하셨어요';
      var message = "\"엄마가 그런 짓 하면 안 돼!\"라고 하셨어요";
    • 자료형 반환: typeof
    • var a = 100; var message = "hi" console.log(typeof a); console.log(typeof message);
       
    • undefined, null, NaN
    • var b; console.log(b) // undefined
       
    • boolean = 참, 거짓
    • var c = true
      console.log( 1 > 100 );
       
    • 값과 참조
      • 기본 자료형은 값 의미를 가진다
      • var a = 100; var b = a; // 값 의미 a = 100; console.log(a, b);

배열

  • 콩을 둘러싼 콩깍지
    • var a = [1, 2, 3, 4, 5]; console.log(a); console.log(a[2])
  • 배열의 인덱스는 0부터
  • JS에서 배열은 아무 자료형이나 섞어서 쓸 수 있다.
    • var b = '비'; var a = [1, 2, b, 4, 5]
  • 배열의 원소 수는 length 를 사용
    • var b = '비'; var a = [1, 2, b, 4, 5, 10000] console.log( a.length )
  • 배열에 데이터 추가 - push()
    • var b = '비' var a = [1, 2, b, 4, 5, 10000] console.log( a.length ) a.push('하하하') console.log( a )
  • 빈 배열에 값 넣기 -1-
    • var a = [] a.push(1) a.push(3)
  • 빈 배열에 값 넣기 -2-
    • var a = [] a[0] = 1 a[1] = 3 // 헐! 이게 된다고???? 😳
       

연산자

  • 산술 연산자: +, -, *, /
    • var a = 100 var b= 200 console.log( a + b )
  • 문자열 더하기: +
    • var message1 = '안녕? 내 이름은 ' var message2 = '일분이고, 나이는 ' var age = 7 console.log(message1 + message2 + age + '살 이야.')
       
  • 축약형
    • var a = 1 a += 1 a -= 1 a++ ++a
  • 비교 연산자: < <= > >=
    • var a = 100 var b = 200 console.log( a < b )
  • 같다, 같지 않다: ==, ===, !=
    • var a = 100 var b = '100' console.log( a == b ) // TRUE!!!! 😳 console.log( a === b ) // 정확하게 일치
  • 논리 연산자: 그리고(&&), 또는(||), 부정(!)
    • var a = 100 var b = 200 console.log( a < 200 && a == 100 ) console.log( !true ) console.log( !(100 > 200) )
 

조건문

  • if ... else ...
    • var age = 100 if (age > 18) { console.log( '성인' ) } else if (age > 13 { console.log( '청소년') } else if (age > 7) { console.log( ' 어린이' ) } else { console.log( '유아' ) }
  • 무조건 논리 연산자를 사용해서 조건을 정하기보다 중복을 줄이고 간결한 코드를 쓰는 게 바람직!
 

반복문

  • for
    • for (var i = 0; i < 10; i++) { console.log(i) }
  • 유연한 for 문 - 세상에, 이게 된다고????
    • var i = 0 for (; i < 10; i++) { console.log(i) }
 

반복문을 이용해 배열 출력하기

  • 배열 enumeration. 전통적인 C 방식
    • var movies = ["어벤저스", "오펀", "강시", "나 홀로 집에", "내부자들"] for (var i = 0; i < movies.length; i++) { console.log(movies[i]) }
 

함수란?

  • 함수: 특정 기능을 하는 코드 덩어리
    • function sample() { console.log('ㅋㅋㅋㅋㅋㅋㅋㅋ') } sample()
  • ECMA2015 등에서 여러 가지 다양한 함수 표현이 등장함
 

매개변수

  • 함수에 전달되는 인수. 파라미터.
    • function 더하기(a, b) { console.log( a + b ) } 더하기(1, 100) function 인사(이름) { console.log("안녕? 나는 " + 이름 + "이야!") } 인사('일분이')
 

return 리턴 값

  • return: 함수를 종료하고 호출한 곳으로 되돌아감.
  • 리턴값: 함수를 호출한 곳으로 되돌려주는 값
    • var a = 100 function sample() { if (a > 0) { return } document.('ㅋㅋㅋㅋㅋㅋㅋㅋ') } sample()
  • 리턴값을 활용하자
<style> body { font-size: 3rem; } h1 { background: #fff000 } </style> function 더하기(a, b) { document.write( a + b ) } h = 더하기(100, 200) console.log(h) // undefined function 뎌하기2(a, b) { document.write(200, 500) return a + b } h = 더하기2(200, 500) console.log(h) document.querrySelector('h1').style.height = h + 'px'
  • 리턴 값이 없는 함수는 undefined
  • 처음 코딩을 접하는 사람들은 return 값이 있거나 없을 경우의 차이를 어려워한다.
    • "그래서 이걸 어디다 쓰는데?"
 

변수의 유효 범위

  • 변수가 가지는 scope.
    • var a = 100 // 전역변수 function sample() { var b = 200 // 지역변수 console.log( a ); } sample() console.log(b) // error!!
       
  • 객체와 스코프
    • function main(){ var jejudo = { a: 100, b: 200, c: 300, configMap: { deviceSize: null, total: 0 } }; console.log(jejudo.a); console.log(jejudo.configMap.total); }
  • letconst: { } 가 유효 범위가 됨. (EMCA2015)
    • if (...) { let a = 100; // 여기서만 유효 }

객체(Object)

  • 객체 만들기
    • var person = {}; person.name = '일분이'; person.age = 12; person.introduce = function () { console.log('안녕? 나는 ' + this.name + ' 야. 나이는 ' + this.age + '살이야.'); } console.log(person); console.log(person.name); person.introduce();
  • 객체에는 속성(property)와 메서드(method)로 한다.
  • 다른 방법으로 객체 만들기
    • var person2 = { name: 'Zena', age: 20, introduce: function() { console.log('안녕? 나는 ' + this.name + ' 야. 나이는 ' + this.age + '살이야.'); } } person2.introduce()
  • JavaScript의 HTML 실행 환경에서는 전역 객체는 window 이고 생략이 가능.
    • alert('111')window.alert('111')과 같다
    • namewindow.name 과 같다.

method 내부의 this

  • 객체 속성은 this로 참조해야 한다.
    • var person2 = { name: 'Zena', age: 20, introduce: function() { console.log('안녕? 나는 ' + this.name + ' 야. 나이는 ' + this.age + '살이야.'); } }; person2.introduce();
 

생성자와 인스턴스

  • 생성자는 함수이다. 객체를 생성하는 역할
    • function Person(username, age) { this.username = username; this.age = age; this.introduce = function() { console.log('안녕? 나는 ' + this.name + ' 야. 나이는 ' + this.age + '살이야.'); } } var p1 = new Person('일분이', 12); var p2 = new Person('Zeno', 20); p1.introduce(); p2.introduce();
    • 인스턴스: 생성자로 생성된 개별 객체들
    • 생성자 함수는 반드시 new 로 호출해야 함.
    • 프로토타입을 이용해서 만들 수도 있고, class를 이용할 수도 있다.
 
 

DOM 스크립트

  • 기본 문서 템플릿
    • <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>DOM: Document Object Model</title> <style> body { font-size: 3rem; } h1 { background: #fff000 } </style> </head> <body> <h1 id="main-title"> DOM (Document Object Model)</h1> <article> <header>header1</header> <section> <header>s header</header> section 1 </section> <section> <header>s header</header> section 2 </section> <script> </script> </body> </html>
  • DOM(Document Object Model): HTML 문서의 감 부분을 객체로 접근하는 방식
 

문서 로딩 기다리기

  • <head> </head> 안에 스크립트 넣기
  • 예전 방식
    • <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>DOM: Document Object Model</title> <style> body { font-size: 3rem; } h1 { background: #fff000 } </style> <script> window.onload = function () { var title = document.getElementByID('main-title'); console.log(title); } </script> </head> <body> <article> <h1 id="main-title"> DOM (Document Object Model)</h1> <header>header1</header> <section> <header>s header</header> section 1 </section> <section> <header>s header</header> section 2 </section> <script> </script> </body> </html>
  • 요즘 방식
    • <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>DOM: Document Object Model</title> <style> body { font-size: 3rem; } h1 { background: #fff000 } </style> <script> window.addEventListener('load', function () { var title = document.getElementByID('main-title'); console.log(title); }); </script> </head> <body> <article> <h1 id="main-title"> DOM (Document Object Model)</h1> <header>header1</header> <section> <header>s header</header> section 1 </section> <section> <header>s header</header> section 2 </section> <script> </script> </body> </html>
       
    • 세 가지 방식의 차이가 있음.
      • 옛날 방식. load 를 쓰는 것과 같은 동작. 새로운 방식으로 선호.
        • window.onload = function () { var title = document.getElementByID('main-title'); console.log(title); }
      • 'load': 웹 페이지가 모두 로드될 때까지 기다림. 이미지나 문서 내용이 많으면 시간이 걸릴 수 있음.
        • window.addEventListener('load', function () { var title = document.getElementByID('main-title'); console.log(title); });
      • 'DOMContentloaded': 문서의 DOM 구조가 로드되면 일단 실행함. 문서의 데이터가 다 로드되지 않더라도 실행이 가능함.
        • window.addEventListener('DOMContentloaded', function () { var title = document.getElementByID('main-title'); console.log(title); });
      • JQuery 에서는...
        • $(function() { .... });
      • 이것은 deprecated... 쓰지 마세요!
        • $(document).ready(function () { .... });
       
       

<script>를 아래에 쓰는 이유

  • 빠른 척을 할 수 있음. 굳이 이벤트 코드를 쓸 필요가 없음.
    • <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>DOM: Document Object Model</title> <style> body { font-size: 3rem; } h1 { background: #fff000 } </style> </head> <body> <article> <h1 id="main-title"> DOM (Document Object Model)</h1> <header>header1</header> <section> <header>s header</header> section 1 </section> <section> <header>s header</header> section 2 </section> <script> var title = document.getElementByID('main-title'); console.log(title); </script> </body> </html>

HTML 엘리먼트 객체 얻기

  • getElementsByID(), getElementsByTagName()...
    • <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>DOM: Document Object Model</title> <style> body { font-size: 3rem; } h1 { background: #fff000 } </style> </head> <body> <article> <h1 id="main-title"> <span>hello</span> DOM (Document Object Model) </h1> <header>header1</header> <section> <header>s header</header> section 1 </section> <section> <header>s header</header> section 2 </section> <script> var title = document.getElementByID('main-title'); var titleSpan = title.getElementsByTagName('span'); console.log(titleSpan[0]); </script> </body> </html>
  • 요즘 쓰는 방식
    • <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>DOM: Document Object Model</title> <style> body { font-size: 3rem; } h1 { background: #fff000 } </style> </head> <body> <article> <h1 id="main-title"> DOM (Document Object Model) <small>small</small> </h1> <header>header1</header> <section> <header>s header</header> section 1 </section> <section> <header>s header</header> section 2 </section> </h1> <script> var mainTitle = document.querySelector('#main-title small'); console.log(titleSpan[0]); </script> </body> </html>
       
    • querySelector(), querySelectorAll() 함수
      • var ilbuni = document.querySelector('.ilbuni'); var ilbunis = document.querySelectorAll('.ilbuni');
    • ilbuni class에 보더 넣기
      • var ibunis = document.querySelectorAll('.ilbuni'); for (var i = 0; i < ilbunis.length; i++) { ilbunis[i].style.border = '1px solid red'; }