웹개발 교육/JavaScript

[7일] JavaScript (1) - 자료형, 연산자

ewok 2022. 8. 3. 17:56

프로그램 언어(Java, Python, C, JSP ...)

기초 : 연산자, 조건문, 반복문, 배열, 함수

 

JavaScript 자바스크립트

  • 웹페이지의 3요소 : 구조(HTML) + 표현(CSS) + 동작(Javascript 또는 웹 프로그래밍 언어)
  • 웹브라우저에서 interpreter방식으로 해석되는 스크립트 언어
  • Server Side Interface : JavaScript
  • on Server : JSP, ASP, PHP ~~~
  • HTML 문서를 좀 더 역동적으로 동작시킬 수 있다
  • jQuery : JavaScript를 라이브러리화 해 놓은 오픈소스

기본 문법

  • 대소문자를 구분한다
  • 종결 문자 ;
  • <script> </script> 안에 작성한다.

컴파일

                                   원시 프로그램 : Source                                                 목적 프로그램 : Object

 

document.write()

본문 <body> 영역에 출력

자료형

1. 숫자형

// 1. 숫자형
    document.write(123);
    document.write(456);
    document.write(789);

 

2. 문자형

문자형은 반드시 ' 또는 " 기호로 감싸야한다.

// 2. 문자형
// 반드시 ' ' 또는 " " 기호로 감싼다
document.write('KOREA');
document.write("SEOUL");   
// document.write("JEJU');    에러 
// document.write(대한민국);   에러

에러가 어디서 발생했는지 확인할 수 있다.

 

3. 논리형 (boolean)

// 3. 논리형 (boolean)
// 맞다(참 True), 틀리다(거짓 False)
document.write(true);
document.write(false);
document.write('true');   //문자형

 

형태 구분

document.write(10);    // 양의 정수
document.write(-20);   // 음의 정수
document.write(3.4);   // 실수
document.write(-5.6);
document.write("false"); // 문자형
document.write('1004');  // 문자형

 

출력

<script>
    // 자바스크립트에서 HTML 태그를 사용하려면, 문자형으로 사용한다
    document.write("대한민국");
    document.write("<br>");
    document.write("오필승 코리아");
    document.write("<hr>");
</script>

 

// 명령어로 사용되는 기호를 단순 기호로 인식하려면 \ 와 같이 사용한다
document.write("\"");
document.write("<hr>");
document.write('\'');
document.write("<hr>");
document.write('\\');
document.write("<hr>");

document.write('"');
document.write('<hr>');
document.write("'");

 

상수와 변수

1. 상수 constant

// 고정 불변의 값
document.write(3);
document.write(-5);
document.write('A');
document.write("가");
document.write(true);
document.write("<hr>");

2. 변수 variable

변하는 값

변수 타입(자료형) : var, let, const, nothing

대입 연산자 형식 : 변수명=값

// 1) var
var a=3; //a라는 변수를 선언하고 3을 저장
var b=5;
var c=7;
document.write(a);  // 변수
document.write(b);
document.write(c);
document.write(a+b+c); // 15
document.write("a"); // 상수
document.write("<hr>");

 

// 2) nothing : 변수 타입을 선언하지 않아도 사용할 수 있다
name="손흥민";
age=25;
height=178.5;
document.write(name);
document.write(age);
document.write(height);
document.write("<hr>");

 

// 변수는 새로운 값으로 대입하면서 사용한다
a=2;
b=4;
c=6;

name="김연아";
age=30;
height=165.9;

document.write(a);
document.write(b);
document.write(c);
document.write(name);
document.write(age);
document.write(height);
document.write("<hr>");

 

// 3) let
// 반드시 변수를 선언하고 사용한다
let i=2;
let j=4;
let k=i+j;
document.write(k); //6

// let i=8; 에러. let으로 선언한 i변수를 이중으로 선언할 수 없다

 

// 4) const
// 변수를 상수화
const x=10;
// x=9; 에러. 변수값을 바꿀 수 없다

※ 식별자 명명 규칙

  1. id명, name명, 변수명, 함수명, 객체명, ...
  2. 식별자 명에 의미를 부여한다.
  3. 영문자와 숫자를 조합해서 작성한다.
  4. 금지 : 한글, 첫 글자로 숫자

 

document

● 객체 object

객체명.멤버함수()

객체명.멤버변수

 

● document 객체

HTML 페이지의 본문 <body> 가리키는 객체

document.write(123);
document.write("대한민국");
document.write("<hr>");

document.write(3+5);           //8
document.write("<hr>");
document.write(3+"5");         //35
document.write("<hr>");
document.write("3"+5);         //35
document.write("<hr>");
document.write("3"+"5");       //35
document.write("<hr>");
document.write("3+5");         //3+5
document.write("<hr>");

 

let name="손흥민";
let age=25;
let height=178.9;
document.write("이름 : " + name + "<hr>");
document.write("나이 : " + age + "<hr>");
document.write("키 : " + height + "<hr>");

 

자바스크립트에서 HTML tag 사용 시 문자열 처리해서 사용

document.write("<hr>");
document.write("개나리<br> <p>진달래</p>");
document.write("<img src='../../images/monkey.png'>");

 

누적

let str=""; // 빈 문자열(글자 개수가 0개)
str = str + "ONE";
document.write(str);

str = str + "TWO";
document.write(str);
document.write("<hr>");

str = str + "THREE"
document.write(str);
document.write("<hr>");

처음 str에 빈 문자열을 선언했다. 그 후 빈 문자열인 기존의 str에 "ONE"을 추가하여 str에 빈 문자열이 아닌 ONE가 들어갔다.

 

자바 스크립트에서 id에 접근할 수 있도록 하는 명령어가 있다.

.getElementById 이다.

// 본문 <body>에 있는 id 속성 접근
// 1) 순수 JavaScript 접근
    document.getElementById("demo");
    document.getElementById("demo").innerHTML="아이티윌";
    
// 2) jQuery 접근 (jQuery 라이브러리)
    $("#demo")
    $("#demo").val("아이티윌")

 

연습

이름, 나이, 키 값들을 표를 작성해서 id=demo에 출력하시오

<body>
    <div id="demo"></div>
    
    <script>
    name = "김연아";
    age = 30;
    height = 165.7;
    
    let result = ""; // 결과값
    
    result = result + "<table border='1'>";
    result = result + "<tr>";
    result = result + "   <th>이름</th>";
    result = result + "   <td>" + name + "</td>";
    result = result + "</tr>";
    result = result + "<tr>";
    result = result + "   <th>나이</th>";
    result = result + "   <td>" + age + "</td>";
    result = result + "</tr>";
    result = result + "<tr>";
    result = result + "   <th>키</th>";
    result = result + "   <td>" + height + "</td>";
    result = result + "</tr>";
    result = result + "</table>";
    
    document.getElementById("demo").innerHTML=result;
	</script>
</body>

 

 

연산자

  • 연산자 Operator
  • 이식성이 풍부하다
  • 산술, 비교, 논리 연산자

 

1. 산술 연산자

document.write(5+3);      // 8
document.write(5-3);      // 2
document.write(5*3);      // 15
document.write(5/3);      // 1.66666667

document.write(3/5);      // 0.6
document.write(3%5);      // 3
document.write("<hr>");

 

2. 비교(관계) 연산자

< , > , =< , >= , == , !=

// 논리형(boolean)으로 반환된다
// true, false
document.write(5>3);    // true
document.write(5<3);    // false
document.write("<hr>");

document.write(5>=3);    // true
document.write(5<=3);    // false
document.write("<hr>");

document.write(5==3);    // false     == 서로 같다
document.write(5!=3);    // true      != 서로 같지 않다
document.write("<hr>");

 

3. 논리 연산자

  • 조건이 2개 이상일 경우 전체적으로 판단
  • 결과값은 boolean 값으로 반환
  • 그리고 또는 , 부정

1) && 연산자

// 그리고, and 연산자, 논리곱
// 모든 조건이 true일때만 true
// ~이면서
document.write(5<3 && 2<4);   //false & true = false

2) || 연산자

// 2) || 연산자
// 또는, or 연산자, 논리합
// 조건들 중에서 하나만이라도 true이면 true
// ~이거나
document.write(5<3 || 2<4);   //false or true = true

3) ! 연산자

// 논리 부정 연산자, not 연산자
// ~ 아니라면
let flag = true;
document.write(!flag);    // !true -> false

연습문제

<h3>연산자 연습문제</h3>
<script>
    //문1) 임의의 정수가 짝수인지 확인하시오
    // 짝수 : 2로 나누어서 나머지가 0 / 2의 배수
    let a = 4;
    document.write(a%2==0);     // 4%2 = 0 == 0. true
    document.write(a%2!=1);     // 4%2 = 0 != 1. true
    document.write("<hr>");
    //문2) 임의의 정수가 3의 배수인지 확인하시오                  
    let b = 7;
    document.write(b%3==0);     // 7%3 = 1 == 0 false
    document.write("<hr>");
    //문3) 임의의 정수가 4의 배수인지 확인하시오
    let c = 4;
    document.write(c%4==0);     // 4%4 = 0 == 0 true
    document.write("<hr>");
    //문4) 해당 년도가 윤년인지 확인하시오
    // 윤년 : 4년마다 한번씩 2월 29일이 속해 있는 연도
    let year = 2022;
    document.write(year%4==0);  // 2022%4 = 2 == 0 false
    //문5) 임의의 정수가 2의 배수이면서 5의 배수인지 확인하시오
    let d = 15;
    document.write(d%2==0 && d%5==0);
            // 15%2 = 1         0 = 15%5
            //        1 == 0    0 == 0
            //        false   &   true = false                    
    
    //문6) 임의의 정수가 1 또는 3인지 확인하시오
    let code = 1;
    document.write(code==1 || code==3);
                    //  1 ==1      1==3
                    //  true  or   false = true
</script>

 

연산자 우선순위

  • 최우선 연산자 : ( )
  • 산술 -> 비교 -> 논리
  • 후순위 연산자 : 대입 연산자 =

1. 결합 연산자

document.write(3+4+5/2);      // 9.5
document.write((3+4+5)/2);    // 6
document.write("<hr>");

2. 대입 연산자

let num = 3;

num = num + 2;
//5 =  3  + 2
document.write(num + "<hr>");

num += 2;
document.write(num);  // 7

num = num - 3;
document.write(num + "<hr>");  // 4

num -= 3;
document.write(num + "<hr>");  // 1

num *= 10;  // num = num * 10
document.write(num + "<hr>");  // 10

num /= 2;
document.write(num + "<hr>");  // 5

num %= 4;  // num = num % 4
document.write(num + "<hr>");  // 1

3. 1증감 연산자

let a = 3;
a = a + 1;  // 4
document.write(a + "<hr>");
a += 1;     // 5
document.write(a + "<hr>");
a++;  // 6
document.write(a + "<hr>");
++a;  // 7
document.write(a + "<hr>");

let b = 3;
b = b-1; // 2
document.write(b + "<hr>");
b -= 1;  // 1
document.write(b + "<hr>");
b--;     // 0
document.write(b + "<hr>");
--b;     // -1
document.write(b + "<hr>");

1증감 연산자는 다른 계산식과 같이 사용할 경우 주의해야 한다.

let c = 10;
let d = 20;
let i = c++; // i=c
             // c=c+1
let j = --d; // d=d-1
             // j=d
document.write(c+d+i+j);  //11 + 19 + 10 + 19
document.write("<hr>");

c+d+i+j는 60이라고 생각할 수 있다. 하지만 59이다.

i = c++ 에서 ++가 c 뒤에 있다. 이 경우 i = c를 먼저 실행한 후 c++가 실행된다. 따라서 i에는 c값이 들어가 i = 10이 되고 c는 1이 증가하여 11이 된다. ( i=10, c=11)

 

j = --d 에서 --가 d 앞에 있다. 이 경우 --d를 먼저 실행한 후 j=d가 실행된다. 따라서 d는 1이 감소하여 19가 되고 j는 d값이 들어가 19가 된다. ( d=19, j=19)

 

따라서 c+d+i+j 는 11+19+10+19가 되어 59이다.