[JavaScript] 자료형

자료형

- 데이터를 다루기 위해 미리 정해놓은 데이터 유형

- 동적 타이핑(Dynamic Typing) : 데이터를 넣은 시점에 자료형 결정

- var, let 등으로 선언

 

 

 

숫자형

- 숫자를 다루기 위한 자료형

- 정수나 실수

// Number type
let n1 = 1234;
let n2 = 5.678;

 

 

 

문자형

- 문자와 문자열을 다루기 위한 자료형

- 문자(열)를 큰따옴표나 작은따옴표로 감싸줌

// String type
let s1 = "hello";
let s2 = 'world';

 

 

 

불리언(Boolean)형

- 값이 true, false로만 이루어진 자료형

// Boolean type
let b1 = true;
let b2 = false;

 

 

 

Null형

- 값이 Null인 자료형

// Null type
let n = null;

 

 

 

Undefined형

- 정의되지 않은 자료형

- 변수를 선언하고 값을 넣지 않거나 undefined를 넣을 때

// Undefined type
let u1;
let u2 = undefined;

 

 

 

배열

- 변수 여러 개를 순서대로 모아둔 것

- 각 요소들은 인덱스 값을 가짐(0부터 시작)

- 다양한 자료형이 섞여서 들어갈 수 있음

// Array type
let arr1 = [1, 2, 3, 4];
let arr2 = ["a", "b", "c", "d", "e"];
let arr3 = [1, "h", 2, "i"];
let arr4 = [true, 1, undefined, "h", null];

document.write(arr1[0]);  // 1
document.write(arr4[3]); // h

 

 

 

객체

: 객체(파이썬에서는 딕셔너리)를 다루기 위한 자료형

: {key : value} 형태로 이루어짐

: key는 문자형이어야 하고 value는 어떤 자료형이든 들어갈 수 있음

: value 출력할 때는 객체[key] 또는 객체.key 로 출력

// Object type
let obj1 = {a : "apple", b : "banana", c : "carrot"};
let obj2 = {a : 1, b : "hello", c : [1,2,3,4]};
let obj3 = {
        a : {a1 : 1, a2 : 2},
        b : {b1 : 3, b2 : 4},
        c : {c1 : 5, c2 : 6},
}

document.write(obj1['a']);  // apple
document.write(obj2.c);  // 1,2,3,4
document.write(obj3.c.c2);  // 6