STUDY/JavaScript

형 변환

aftersep 2022. 12. 26. 16:53

String() : 문자형으로 변환

 

Number(): 숫자형으로 변환

 

Boolean(): 불린형으로 변환

 

형 변환이 필요한 이유 : 자료형이 다르면 의도치 않은 동작이 발생할 수 있기 때문!

 

const mathScore = prompt("수학 몇 점?");
const engScore = prompt("영어 몇 점?");
const result = (mathScore + engScore) / 2;

console.log(result)

이상한 답...

 

=> prompt로 입력 받은 값은 "문자형"이기 때문에 정상적인 계산이 되지 않는다!

90 + 80 = 9080

  const mathScore = 90;
  const engScore = 80;
  const result = (mathScore + engScore) / 2;


  console.log(result)

정상

자동 형변환은 오류를 발생시키거나, 그로 인한 원인을 찾기 어려워지므로 명시적 형변환을 해주는 것이 좋다.

 

 

문자 형변환 : String()

console.log(
String(3),
String(true),
String(false),
String(null),
String(undefined)
  )

 

 

숫자 형변환 : Number()

console.log(
  Number("1234"),
  Number(true),
  Number(false)
  )

 

Boolean()

숫자 0, 빈 문자열 '', null, undefined, NaN = false

console.log(
  Boolean(0),
  Boolean(""),
  Boolean(null),
  Boolean(undefined),
  Boolean(NaN)
  )

 

 

Number(null) // 0
Number(undefined) // NaN
Boolean(0) // false
Boolean('0') // true
Boolean('') // false
Boolean(' ') // true

 

'STUDY > JavaScript' 카테고리의 다른 글

비교 연산자, 조건문  (0) 2022.12.27
연산자  (0) 2022.12.27
alert, prompt, confirm  (0) 2022.12.25
자료형  (0) 2022.12.22
변수  (0) 2022.12.18