반응형

자바스크립트 형 변환

1) 숫자형으로 변환

- 자바스크립트에서 숫자형으로의 변환은 parseInt()와 Number()가 있는데 이 두 함수는 숫자형으로의 변환해주는 함수라는 공통점이 있지만 약간의 다른 점이 있다. 아래 예제를 보면 이해가 쉽다.

ex)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 1. '01'이라는 문자
let strNum = '01';
console.log(parseInt(strNum)); // 결과 : 1
console.log(Number(strNum)); // 결과 : 1
 
// 2. '2021년'이라는 문자
let strNum = '2021년';
console.log(parseInt(strNum)); // 결과 : 2021
console.log(Number(strNum)); // 결과 : NaN
 
// 3. '제 10회'라는 문자
let strNum = '제 10회';
console.log(parseInt(strNum)); // 결과 : NaN
console.log(Number(strNum)); // 결과 : NaN
 
// 4. '12.312'라는 문자
let strNum = '12.312';
console.log(parseInt(strNum)); // 결과 : 12
console.log(parseFloat(strNum)); // 결과 : 12.312
console.log(Number(strNum)); // 결과 : 12.312
cs

- 예제에서 볼 수 있듯이 두 개의 함수는 변환하려는 변수의 형태에 따라 다른 결과값으로 반환하는 것을 볼 수 있다. 따라서 어떤 변수를 어떤 형태로 반환하려는지의 상황에 따라 다르게 사용해야 한다.

 

2) 문자형으로 변환

- 문자형으로의 변환은 String()을 사용한다.

ex)

1
2
3
4
var num = 440;
console.log(num + ' of type is ' + typeof(num)); // 결과 : 1300 of type is number
str = String(num); //date type conversion
console.log(str + ' of type is ' + typeof(str)); // 결과 : 1300 of type is string
cs

 

3) 논리형으로 변환

- 논리형으로의 변환은 Boolean()을 사용한다.

ex)

1
2
3
4
let num = 1;
console.log(num + ' of type is ' + typeof(num)); // 결과 : 1 of type is number
let bool = Boolean(num); //date type conversion
console.log(bool + ' of type is ' + typeof(bool)); // 결과 : true of type is boolean
cs

 

반응형

+ Recent posts