JavaScript Tutorial.48

ansunny1170·2022년 1월 3일
0
post-thumbnail

JS Type Conversion

  • Converting Strings to Numbers
  • Converting Numbers to Strings
  • Converting Dates to Numbers
  • Converting Numbers to Dates
  • Converting Booleans to Numbers
  • Converting Numbers to Booleans

JavaScript Type Conversion

JavaScript 변수는 새 변수 혹은 다른 데이터 type 으로 변환할 수 있다.

  • JavaScript 함수를 사용한 방법
  • JavaScript 자체 자동으로

Converting Strings to Numbers

전역 메서드 Number()는 문자열을 숫자로 변환 시킬 수 있다.

숫자를 포함하는 문자열(예: "3.14")은 숫자(예: 3.14)로 변환된다.

빈 문자열은 0으로 변환된다.

다른 모든 것은 NaN(숫자가 아님)으로 변환됩니다.

Number Methods

Number Methods 장에서 문자열을 숫자로 변환하는 데 사용할 수 있는 더 많은 방법을 찾을 수 있다.

MethodDescription
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

The Unary + Operator

단항 + 연산자는 변수를 숫자로 변환하는 데 사용할 수 있다.

변수를 변환할 수 없는 경우에도 여전히 숫자가 되지만 값은 NaN(숫자가 아님)이다.

Converting Numbers to Strings

  • 전역 메서드 String()은 숫자를 문자열로 변환할 수 있다.

모든 유형의 숫자, 리터럴, 변수 또는 표현식에 사용할 수 있다.

  • Number 메서드 toString()도 동일한 작업을 수행한다.

More Methods

Number Methods 장에서 숫자를 문자열로 변환하는 데 사용할 수 있는 더 많은 방법을 찾을 수 있다.

MethodDescription
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

Converting Dates to Numbers

  • 전역 메서드 Number()를 사용하여 날짜를 숫자로 변환할 수 있다.

  • data 메서드 getTime()도 동알하게 작동한다.

Converting Dates to Strings

  • 전역 메서드 String()는 dates를 string으로 변환할 수 있다.

  • Date 메서드 toString()도 동일하게 작동한다.

Date Methods 장에서 날짜를 문자열로 변환하는 데 사용할 수 있는 더 많은 방법을 찾을 수 있다.

MethodDescription
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)

Converting Booleans to Numbers

  • 전역 메서드 Number() 역시 booleansnumbers로 변환 시킬 수 있다.

Converting Booleans to Strings

전역 메서드 String()booleansnumbers로 변환 시킬 수 있다.

Booleans 메서드 toString()도 동일하게 동작한다.

Automatic Type Conversion

JavaScript가 "잘못된" 데이터 유형에서 작동하려고 하면 값을 "올바른" 유형으로 변환하려고 시도한다.

결과가 항상 기대하는 것과 같지는 않다.

Automatic String Conversion

JavaScript는 객체 또는 변수를 "출력"하려고 할 때 자동으로 변수의 toString() 함수를 호출한다.

numbers와 boolenas도 변환되지만 잘 알아 차리기 힘들다.

JavaScript Type Conversion Table

다음 표는 다양한 JavaScript 값을 숫자, 문자열 및 booleans로 변환한 결과를 보여준다.

사이트 참고
(참조 : https://www.w3schools.com/js/js_type_conversion.asp)

따옴표 안의 값은 문자열 값을 나타낸다.

빨간색 값 은 프로그래머가 예상하지 못한 값(일부)을 나타낸다.

profile
공정 설비 개발/연구원에서 웹 서비스 개발자로 경력 이전하였습니다. Node.js 백엔드 기반 풀스택 개발자를 목표로 하고 있습니다.

0개의 댓글