Web/javascript

JavaScript 변수, 데이터 타입, 타입변환 함수, 연산자

dustKim 2024. 4. 15. 22:07
자바스크립트의 특징

- 객체 기반의 스크립트 언어로, 대소문자를 구별하고, 문장 끔에 ;(세미콜론)을 사용한다. ;(세미콜론)은 생략이 가능하다.

 

자바스크립트의 출력

- Web API Console을 통해 브라우저 Console 창에 출력한다.

 

자바스크립트의 삽입 방법
1.	<script>
		코드작성
	</script>

2. 	<script src="파일명"></script>
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>자바스크립트 출력</title>
    <script>
        console.log("안녕하세요! 자바스크립트");
    </script>
</head>
<body>
    <h2>자바스크립트 출력</h2>
    <script>
        console.log("자바스크립트 출력!");
    </script>
</body>
</html>
결과

 

주석문

- // : 한 줄 주석

- /* 내용 */ : 여러 줄 주석

 

변수

- 데이터를 저장한 값을 가리키는 메모리 공간이다.

- 값은 변경될 수 있다.

- 자바스크립트의 변수는 타입이 없다.

- let 키워드를 사용하여 변수를 선언한다.

# 파이썬과 자바스크립트의 변수 선언

파이썬
name = "파이썬"

자바스크립트
let name = "자바스크립트";
(큰 따옴표("")와 작은 따옴표('')를 구별하지 않음)


# 자바스크립트 변수 사용 예
console.log(num); # 값을 넣지 않고 사용할 경우 undefined
var num = 10;

{
    console.log(num); # 전역변수 num = 10
    var num = 20
}
console.log(num); # 지역변수 num = 20

 

let

- 지역변수, 전역변수의 구별이 확실하다.

- 같은 이름의 변수를 선언할 수 없다.

 

트랜스 컴파일러

- 과거 브라우저 및 특정 브라우저 버전 등을 모두 사용할 수 있도록 해석해 주는 라이브러리이다. (BABEL 등)

 

상수(constant)

- 한번 선언된 상수는 다시 재정의 할 수 없다.

- 값을 재할당 할 수 없다.

- 개발자의 실수를 방지하기 위해 권장한다.

- 해킹을 방지하기 위한 목적이 있다.

let name;   #변수의 선언
name = "김사과";  # 값 할당

let name = "김사과";  # 변수의 선언 및 할당

const name;
name = "김사과";  (X) # 에러

const name = "김사과";  (O)  # 값을 못바꿈

 

데이터 타입(Data Type)

- 프로그램에서 다룰 수 있는 값의 종류이다.

- 자바스크립트는 선언시 타입을 정하지 않기 때문에 많은 문제가 발생할 수 있다.

- 자바스크립트의 타입 유연성을 해결하기 위해 MS에 만든 타입스크립트가 존재한다.

 

  • 숫자형(Number)

- 정수와 실수를 따로 구분하지 않는다.

- 모든 수를 실수 하나로만 표현한다.

더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>데이터 타입</title>
</head>
<body>
    <h2>데이터 타입</h2>
    <script>
        // number 형
        const num1 = 10;
        const num2 = 11.11;
        const num3 = 10e6;
        console.log(num1);
        console.log(num2);
        console.log(num3);
        console.log(typeof(num1));
        console.log(typeof(num2));
        console.log(typeof(num3));
    </script>
</body>
</html>
결과

 

  • 문자형(String)

-  ' ', " ", ``로 둘러싸인 문자의 집합이다.

더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>데이터 타입</title>
</head>
<body>
    <h2>데이터 타입</h2>
    <script>
        // string 형
        const num4 = 10;
        const num5 = 5;
        const str1 = "Hello JavaScript";
        const str2 = "Hello World";
        const str3 = "10"
        console.log(typeof(str3));
        console.log(num4 + num5);
        console.log(num4 + str1);
        console.log(str1 + str2);
        console.log(str1 + ' ' + str2);
        console.log(`${str1} ${str2}`);
        console.log(`자바스크립트에서 문자열은 
        큰 따옴표 또는 작은 따옴표로 둘러싸인 
        문자의 집합을 의미한다.`)
        console.log(num4 + str3);
        console.log(num4 - str3);  // 자동형변환
        console.log(num4 * str3);
        console.log(num4 / str3);
    </script>
</body>
</html>
결과

 

  • 논리형(Boolean)

- 참(true), 거짓(false)으로 표현되는 값이다.

- false, 0, '', nul, undefined는 모두 거짓(false)으로 판정한다.
- false가 아닌 모든 값은 참(true)으로 판정한다.

더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>데이터 타입</title>
</head>
<body>
    <h2>데이터 타입</h2>
    <script>
        // 논리형
        const b1 = true;
        const b2 = false;
        console.log(typeof(b1));
        console.log(typeof(b2));
        console.log(10 > 5);
        console.log(10 < 5);
    </script>
</body>
</html>
결과

 

  • undefined

- 타입이 정해지지 않은 타입이다.(변수 선언 후 값이 정해지지 않은 경우)

더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>데이터 타입</title>
</head>
<body>
    <h2>데이터 타입</h2>
    <script>
        // undefined
        let num;
        console.log(num);
        console.log(typeof(num));
    </script>
</body>
</html>
결과

 

  • null

- null을 저장한 값이다.
- 값이 없는 것(객체)

더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>데이터 타입</title>
</head>
<body>
    <h2>데이터 타입</h2>
    <script>
        // null
        let obj1 = {};
        console.log(obj1);
        console.log(typeof(obj1));
        let obj2 = null;
        console.log(obj2);
        console.log(typeof(obj2)); // type은 object
    </script>
</body>
</html>
결과

 

  • 심볼형(Symbol)

- 유일하고 변경 불가능한 기본값을 만든다.

- 객체 속성의 key로 많이 사용한다.
    const sym1 = Symbol("apple");
    const sym2 = Symbol("apple");

 

  • 객체형(Object)

- 어떤 속성을 하나의 변수에 저장할 수 있게 해주는 집합이다.
- key value pair 구조로 저장한다.

 

자동 타입 변환

- 특정 타입의 값을 기대하는 곳에 다른 타입의 값이 오면 자동으로 타입을 변환해서 사용한다.

 

타입변환 함수

- 강제로 타입을 변환하는 함수

    Number(): 문자를 숫자형으로 변환한다.
    String(): 숫자나 불린 등을 문지형으로 변환한다.
    Boolean(): 문자나 숫자 등을 불린형으로 변환한다.
    Object(): 모든 자료형을 객체형으로 변환한다.
    ParseInt(): 문자를 소수 없는 정수형으로 변환한다.
    TarseFloat(): 문자를 실수형으로 변환한다.

더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>타입 변환</title>
</head>
<body>
    <h2>타입 변환</h2>
    <script>
        console.log(10 + "문자열");
        console.log('3' * '5');
        console.log(1 - "문자열");

        const num1 = '10';
        const num2 = '5';
        console.log(`현재 num1의 타입:${typeof(num1)}`);
        console.log(`현재 num2의 타입:${typeof(num2)}`);
        console.log(`Number(num1)의 타입:${typeof(Number(num1))}`);
        console.log(`Number(num2)의 타입:${typeof(Number(num1))}`);
        console.log(`String(num1)의 타입:${typeof(String(num1))}`);
        console.log(`Boolean(num1)의 타입:${typeof(Boolean(num1))}, ${Boolean(num1)}`);
        console.log(`Object(num1)의 타입:${typeof(Object(num1))}, ${Object(num1)}`);
        console.log(`ParseInt(num1)의 타입:${typeof(parseInt(num1))}, ${parseInt(num1)}`);
        console.log(`Parsefloat(num1)의 타입:${typeof(parseFloat(num1))}, ${parseFloat(num1)}`);

        console.log("--------------");
        console.log(`num1 + num2 = ${num1 + num2}`);
        console.log(`num1 + num2 = ${Number(num1) + Number(num2)}`);
        console.log(`num1 + num2 = ${parseInt(num1) + parseInt(num2)}`);

    </script>
</body>
</html>
결과

 

자바스크립트의 대화상자

- Web AIP: 브라우저에서 제공하는 API(Application Programming Interface)

    alert(): 사용자에게 메세지를 보여주고 확인을 기다린다.
    confirm(): 사용자에게 메세지를 보여주고 확인이나 취소를 누르면 그 결과를 불린값으로 반환한다.
    prompt(): 사용자에게 메세지를 보여주고 사용자가 입력한 문자열을 반환한다.

더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>대화상자</title>
</head>
<body>
    <h2>대화상자</h2>
    <script>
        const num1 = prompt("첫번째 숫자를 입력하세요");
        const num2 = prompt("두번째 숫자를 입력하세요");
        console.log(num1 + num2);
        console.log(Number(num1) + Number(num2));

    </script>
</body>
</html>
결과

 

연산자
  • 산술 연산자 : +, -, *, /, %, **

 

  • 비교 연산자 :  >, <, >=, <=, ==, !=, ===, !==

    === : 두 식의 값이 같고, 타입이 같아야 함
    예)
        3 == 3 >> true
        '3' == 3 >> true
        '3' === 3 >> false
    !== : 두 식의 값이 다르고, 타입까지 달라야 함

 

  • 대입 연산자 : =, +=, -=, *=, /=, %=, **=
  • 증감 연산자 : ++변수, --변수, 변수++, 변수--

    예)
        let num = 10;
        ++num  // 11     num = num + 1
        --num  // 10     num = num - 1
        num++  // 11     num = num + 1
        num--  // 10     num = num - 1

        let num = 10;
        result = ++num;  // num = 11, result = 11
        result = num++;  // num = 12, result = 11

 

  • 논리 연산자 : &&(and), ||(or), !(not)
  • 비트 연산자 : &(and), |(or), !(not), ^(xor), <<(left shift), >>(right shift)
  • 삼항 연산자

     변수 = 조건식 ? 반환값1 : 반환값2
    - 조건식의 결과가 true일 때 반환값1이 변수에 저장
    - 조건식의 결과가 false일 때 반환값2가 변수에 저장