프로그래밍/Javascript

JS 의 자료형과 형변환

matte 2020. 12. 23. 16:35

 Dynamic typing

JavaScript is a loosely typed and dynamic language. Variables in JavaScript are not directly associated with any particular value type, and any variable can be assigned (and re-assigned) values of all types

 

JavaScript types

The set of types in the Javascript language consists of primitive type and reference type:


 Primitive type

All types except objects define immutable values (that is, values which can't be changed). For example (and unlike in C), Strings are immutable. We refer to values of these types as "primitive values"

  • Boolean, Null, Undefined, Number, BigInt, String, Symbol

 

 Reference type

  • Object
    • Array, Function, Date, RegExp
    • Map, WeakMap, Set, WeakSet ( add in ES6 )

 

 

🎈 Number type

- number type literal 2진수, 16진수 정수 literal 은 표기법일 뿐, 내부적으로는 10진수 정수와 같은 형태로 다뤄진다

7; // 정수 리터럴
2.5; // 부동 소수점 리터럴
0b111; // 2진수 리터럴 (binary literal)
0xf5; // 16진수 리터럴 (hexademical literal)

- JS 는 정수와 실수를 별도의 type 으로 다루지 않는다. 다만 isInteger 메소드로 판별은 가능하다

Number.isInteger(1); // true
Number.isInteger(0.1); // false

- JS 는 정수도 실수와 똑같은 방식(부동소수점)으로 처리하기 때문에 큰 정수에 대해 다음과 같은 표현 및 연산의 오차를 보인다. 정확한 연산을 필요로 한다면 전용 라이브러리를 사용해야 한다

10000000000000001 + 10000000000000002; // 20000000000000000
12345678901234567890; // 12345678901234567000

 


 

 JS 의 자동 형변환

+=, *= 등의 연산자를 사용해 JS 묵시적으로 자동 형변환이 일어나게 한다

var type = 2
type += "";
alert(typeof type);  // Result: string

var type = "2"
type *= 1;
alert(typeof type);  // Result: number

 

  타입변환함수인 Number(), String()

var type = 2 
alert(typeof type);   // Result: number
type = String(type);
alert(typeof type);   // Result: string

var type = "2"
alert(typeof type);  // Result: string
type = Number(type); 
alert(typeof type);  // Result: number

 

  parseInt(), parseFloat() 로 형변환 가능

파싱하는 함수이고, 형변환에 사용하는 함수는 아니다

var tt = "2"
alert(typeof tt);    // Result : string
tt = parseInt(tt);
alert(typeof tt);    // Result : number
            
tt = "2"
alert(typeof tt);    // Result : string
tt = parseFloat(tt);
alert(typeof tt);    // Result : number

 

parseInt 를 사용한 자료형에 대해 NaN 이 나온다 ..?

 

참고