Elegant Developer

javaScript - 자료형(Data Type), 자료형검사(typeof) 본문

FrontEnd/javaScript

javaScript - 자료형(Data Type), 자료형검사(typeof)

혀니D 2017. 8. 21. 18:57

javaScript - 자료형(Data Type)


자바스크립트의 자료형(Data Type)은 여러종류의 데이터를 식별하는 분류이다.

프로그래밍 언어에서 필수 학습중 하나가, 자료형을 파악하는것으로부터 시작이다.


형변환(Type Conversion)에는 암시적(Explicit)과 명시적(Implicit) 두가지가 있다.

자세히 알고 싶으면 URL을 눌러 주세요~

URL : http://developer92.tistory.com/11




- 기본 자료형(Primitive Data Type)

                                      • Boolean

                                      • Null

                                      • Undefined

                                      • Number

                                      • String

                                      • Symbol (ECMASript 6에 추가됨)


 - 객체형(Object Type)

                                        • Object

자료형은 크게 기본형(Primitive Data Type)과 객체형(Object Type)으로 나뉜다.

1
2
3
4
5
6
7
8
9
10
11
12
13
var a = false;        // Boolean
var b = null;         // Null
var c = undefined;    // Undefined
var d = 5;            // Number
var e = '';           // String
var f = Symbol('');   // Symbol
 
 // Object
var g = {};
var h = [];
var i = function() {}
 
 
cs



기본 자료형(Primitive Data Type)


Primitive Data Type의 값은 변경 불가능한 값(Immutable value)이다.

이러한 값을 'Primitive values'라고 한다.




Boolean

Boolean은 논리적인 요소로 나타내며, true와 false 값만을 가진다.


1
2
3
4
var t = true;
var f = false;
 
 
cs




Null

null 타입은 딱 한가지 값, null을 가질 수 있다.

객체를 null로 설정하여 객체를 비울 수 있다.

또한 null의 typeof는 null이 아니라 object이다.


1
2
3
4
5
6
7
8
9
10
var hyeon = null;
typeof hyeon;
 // value : null, typeof : object
 
var person = {name:"hyeon", age:"20", eyeColor:"black"};
var person = null;
document.getElementById('person').innerHTML = typeof person;                                                 
 // value : null, typeof : object
 
 
cs




Undefined

값을 할당하지 않은 변수는 undefined 값을 가진다.

선언은 하였는데 값을 할당하지 않았거나, 해당하지 않는 프로퍼티에 접근할 경우 반환된다.


1
2
3
4
5
6
7
8
9
10
var hyeon;
typeof hyeon;
 // value : undefined, typeof : undefined
 
var person = {name:"hyeon", age:"20", eyeColor:"black"};
var person = undefined;
document.getElementById('person').innerHTML = typeof person;
 // value : undefined, typeof : undefined
 
 
cs



null과 undefined의 차이점

1
2
3
4
5
6
7
typeof undefined  // undefined
typeof null       // object
 
null === undefined  // false
null == undefined   // true
 
 
cs




Number

숫자의 자료형은 단 하나만 존재한다.

배정밀도 64비트 형식 IEEE 754 값(-(253 -1) 와 253 -1 사이의 숫자값),

단 하나만 존재한다. 정수만을 표현하기 위한 특별한 자료형은 없다.


세가지 의미있는 몇가지 상징적인 값들이 있다.

+ Infinity(무한대), - Infinity(무한대), NaN(숫자가 아님)

 

1
2
3
4
5
6
7
8
9
10
var hyeon = 42 / +0;
console.log(hyeon);   // Infinity
 
var _hyeon = 42 / -0;
console.log(hyeon);   // -Infinity
 
var N_hyeon = 1 * 'string';
console.log(N_hyeon)  // NaN(not-a-number)
 
 
cs




String

String Type은 텍스트 데이터를 나타내는데 사용한다.

이는 16비트 부호없는 정수 값 요소들의 집합이다.

String의 길이는 String이 가지고 있는 요소의 갯수이다.

String은 작은 따옴표( '' ) or 큰 따음표( "" ) or 이스케이프에 넣어 생성한다.



문자열은 배열처럼 인덱스 접근이 가능하다.

그러나 이미 할당된 값을 대입하여 변경하는것은 불가능(immutable)하다.

1
2
3
4
5
6
7
8
9
var str = 'string';
 
console.log(str[0]);           // s
console.log(str.toUpperCase);  // STRING
 
console.log(str[0= 'j');     // 에러는 뜨지 않지만 대입이 안됨.
console.log(str);              // string
 
 
cs



이스케이프

이스케이프 시퀀스 

문자 

 영문

\b

백스페이스

Backspace

\t

수평 탭

Tab

\n

줄 바꿈

Newline, Line feed

\f

용지 공급

form feed

\r

캐리지 리턴

Carriage return

\"

이중 따옴표

Duble quotation

\'

단일 따옴표

Single quotation

\\ 

역슬래시 

Back slash 




Symbol

Symbol은 ECMAScript6에서 추가되었다.

Symbol은 유일하고 변경 불가능한(Immutable) 기본값이다(Primitive value)이다.

Symbol은 생성되면 변경되지 않고, 속성을 부여할 수도없다.(시도할시 TypeError 발생)

Symbol은 속성이름으로 사용할수 있으며, 유일하게 Symbol 값을 키로 갖는 프로퍼티이고,

어떤 프로포티와도 충돌하지 않는다.


1
2
3
4
5
6
7
8
9
10
11
var sym = Symbol('sym');
console.log(typeof sym);     // Symbol
 
var obj = {};
obj[sym] = 'value';
obj.hyeon = 'hyeon';         // key/value 추가(add)
console.log(obj[key]);       // value
 
console.log(obj);            // {hyeon: "hyeon", Symbol(key): "value"}
 
 
cs






Object(Type,   참조형)

기본자료형(Primitive)을 제외한 나머지 값들은 모두 객체이다.

데이터를 의미하는 프로퍼티(Property)와 동작을 의미하는 메소드(method)를 말한다.


                                    • 함수 ( Function )

                                    • 배열 ( Array )

                                    • 날짜 ( Date )

                                    • 정규식 ( RegExp )



--------------------------------------------------------------------



자료형검사( typeof )


숫자(Number), 문자(String), 불린(Boolean) 등과 같은 것을 자료형(자료의 형태)라고 부릅니다.

자료형을 확인하려면 typeof 연산자를 사용하면 됩니다.


typeof 연산자는 괄호를 사용하지 않고 사용할 수 있지만, 

괄호를 사용하지 않으면 범위가 어떻게 지정되는지 헷갈릴 수 있습니다.

 

1
2
3
4
5
typeof 1 + 'String';    // numberString
typeof (1 + 'String');  // string
typeof (1+ 'String';  // numberString
 
 
cs

aa

Comments