JavaScript 변수는 새 변수 혹은 다른 데이터 type 으로 변환할 수 있다.
전역 메서드 Number()
는 문자열을 숫자로 변환 시킬 수 있다.
숫자를 포함하는 문자열(예: "3.14")은 숫자(예: 3.14)로 변환된다.
빈 문자열은 0으로 변환된다.
다른 모든 것은 NaN
(숫자가 아님)으로 변환됩니다.
Number Methods 장에서 문자열을 숫자로 변환하는 데 사용할 수 있는 더 많은 방법을 찾을 수 있다.
Method | Description |
---|---|
Number() | Returns a number, converted from its argument |
parseFloat() | Parses a string and returns a floating point number |
parseInt() | Parses a string and returns an integer |
단항 + 연산자는 변수를 숫자로 변환하는 데 사용할 수 있다.
변수를 변환할 수 없는 경우에도 여전히 숫자가 되지만 값은 NaN
(숫자가 아님)이다.
String()
은 숫자를 문자열로 변환할 수 있다.모든 유형의 숫자, 리터럴, 변수 또는 표현식에 사용할 수 있다.
toString()
도 동일한 작업을 수행한다.Number Methods 장에서 숫자를 문자열로 변환하는 데 사용할 수 있는 더 많은 방법을 찾을 수 있다.
Method | Description |
---|---|
toExponential() | Returns a string, with a number rounded and written using exponential notation. |
toFixed() | Returns a string, with a number rounded and written with a specified number of decimals. |
toPrecision() | Returns a string, with a number written with a specified length |
전역 메서드 Number()
를 사용하여 날짜를 숫자로 변환할 수 있다.
data 메서드 getTime()
도 동알하게 작동한다.
전역 메서드 String()
는 dates를 string으로 변환할 수 있다.
Date 메서드 toString()
도 동일하게 작동한다.
Date Methods 장에서 날짜를 문자열로 변환하는 데 사용할 수 있는 더 많은 방법을 찾을 수 있다.
Method | Description |
---|---|
getDate() | Get the day as a number (1-31) |
getDay() | Get the weekday a number (0-6) |
getFullYear() | Get the four digit year (yyyy) |
getHours() | Get the hour (0-23) |
getMilliseconds() | Get the milliseconds (0-999) |
getMinutes() | Get the minutes (0-59) |
getMonth() | Get the month (0-11) |
getSeconds() | Get the seconds (0-59) |
getTime() | Get the time (milliseconds since January 1, 1970) |
Number()
역시 booleans
를 numbers
로 변환 시킬 수 있다.전역 메서드 String()
은 booleans
를 numbers
로 변환 시킬 수 있다.
Booleans 메서드 toString()
도 동일하게 동작한다.
JavaScript가 "잘못된" 데이터 유형에서 작동하려고 하면 값을 "올바른" 유형으로 변환하려고 시도한다.
결과가 항상 기대하는 것과 같지는 않다.
JavaScript는 객체 또는 변수를 "출력"하려고 할 때 자동으로 변수의 toString()
함수를 호출한다.
numbers와 boolenas도 변환되지만 잘 알아 차리기 힘들다.
다음 표는 다양한 JavaScript 값을 숫자, 문자열 및 booleans로 변환한 결과를 보여준다.
사이트 참고
(참조 : https://www.w3schools.com/js/js_type_conversion.asp)
따옴표
안의 값은 문자열 값을 나타낸다.
빨간색 값 은 프로그래머가 예상하지 못한 값(일부)을 나타낸다.