이번시간에도 앞의 강좌에 이어 형변환에 대해서 알아보겠습니다.
이번에는 논리형인 Boolean으로 변경하는 방법에 대해 알아보겠습니다.
이제 좀 감이 오죠. Number(), String(), Boolean() ^^ 자바스크립트는 형변환이 이런식으로 구성되어있네요.
사용방법도 똑같
Boolean(변수)
Boolean()은 boolean형으로 데이터를 변환합니다.
그럼 어떤 식으로 나오는지 봐봅시다.
숫자를 Boolean에 넣어보면 어떻게 될까요?
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>EVERDEVEL - JavaScript - type conversion</title> <script> var num = 440; document.write(num + ' of type is ' + typeof(num) + '<br>'); var bool = Boolean(num); //date type conversion document.write(bool + ' of type is ' + typeof(bool)); </script> </head> <body> </body> </html>
결과를 보시면 아시겠지만 숫자 440을 논리자료형으로 변경하면 값이 true가 됩니다.
또 해볼까요?
문자열 아무거나 넣어서 불리언형으로 변경하면 어떤 값이 나오는지 봅시다.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>EVERDEVEL - JavaScript - type conversion</title> <script> var str = "440"; document.write(str + ' of type is ' + typeof(str) + '<br>'); var bool = Boolean(str); //date type conversion document.write(bool + ' of type is ' + typeof(bool)); </script> </head> <body> </body> </html>
문자열 440도 true를 반환하네요. ^^
자 그럼 몇개 더 해봅시다. 이번엔 숫자 0을 불리언형으로 변경해봅시다.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>EVERDEVEL - JavaScript - type conversion</title> <script> var num = 0; document.write(num + ' of type is ' + typeof(num) + '<br>'); var bool = Boolean(num); //date type conversion document.write(bool + ' of type is ' + typeof(bool)); </script> </head> <body> </body> </html>
숫자 0은 보니까 false를 반환하죠?
숫자 0, null형 null, undefined형 undefined, 문자열 공백은 Boolean형으로 변환하면 false를 반환합니다.
그외의 값은 true를 반환합니다.
문자열로 false를 대입하더라도 문자열이고 공백이 아니기 때문에 Boolean형으로 바꿔본다면 true가 됩니다.
해봅시다.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>EVERDEVEL - JavaScript - type conversion</title> <script> var str = "false"; document.write(str + ' of type is ' + typeof(str) + '<br>'); var bool = Boolean(str); //date type conversion document.write(bool + ' of type is ' + typeof(bool)); </script> </head> <body> </body> </html>
봐주셔서 감사합니다. 문의 또는 잘못된 설명은 아래의 댓글에 부탁드립니다.
당신의 작은 누름이 저에게는 큰 희망이 됩니다.
댓글 0개
정렬기준