ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [javascript] 31. 형 변환(type conversion) - 자바스크립트 강좌 JS / CSE
    Web/JavaScript 2015. 6. 13. 15:22
    JavaScript Type Conversion

     Number() 메소드는 숫자로 변환하고, String() 메소드는 문자열로 변환하고, Boolean() 메소드는 부울 값으로 변환합니다.




    1. JavaScript Data Types

     자바스크립트는 5가지 타입을 가지고 있습니다:
      - string
      - number
      - boolean
      - object
      - function

     3개의 객체 타입이 있습니다:
      - Object
      - Date
      - Array

     2개의 값을 포함하지 않는 타입이 있습니다:
      - null
      - undefined





    2. The constructor Property

     constructor 속성은 모든 자바스크립트 변수의 생성자 함수를 반환합니다.

     
    1
    2
    3
    4
    5
    6
    7
    8
     
    "John".constructor                 // Returns function String()  { [native code] }
    (3.14).constructor                 // Returns function Number()  { [native code] }
    false.constructor                  // Returns function Boolean() { [native code] }
    [1,2,3,4].constructor              // Returns function Array()   { [native code] }
    {name:'John', age:34}.constructor  // Returns function Object()  { [native code] }
    new Date().constructor             // Returns function Date()    { [native code] }
    function () {}.constructor         // Returns function Function(){ [native code] }
    cs

     


     constructor 속성을 통해 객체가 배열인지 찾을 수 있습니다.


     

    1
    2
    3
    function isArray(myArray) {
        return myArray.constructor.toString().indexOf("Array") > -1;
    }
    cs



     또한, 객체가 Date인지도 찾을 수 있죠.


     

    1
    2
    3
    4
     
    function isDate(myDate) {
        return myDate.constructor.toString().indexOf("Date") > -1;
    }
    cs

     





    3. JavaScript Type Conversion

     자바스크립트 변수는 새로운 변수나 다른 데이터 타입으로 변환 될 수 있습니다:

      - 자바스크립트 함수를 사용하여

      - 자바스크립트 자체에서 자동적으로





    3-1. Converting Numbers to Strings

     전역(global) 메소드인 String()​은 숫자를 문자열로 바꿔 줍니다.


     숫자, 문자, 변수, 식 어떤 타입이든 사용 가능  합니다:



     

    1
    2
    3
    String(x)         // returns a string from a number variable x
    String(123)       // returns a string from a number literal 123
    String(100 + 23)  // returns a string from a number from an expression
    cs



     toString() 메소드 또한 동일 합니다.


     

    1
    2
    3
    x.toString()
    (123).toString()
    (100 + 23).toString()
    cs




     

    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

     

     [ 출처: W3Schools ]











    3-2. Converting Booleans to Strings

     전역 메소드 String()은 부울 값을 문자열로 바꿔 줍니다.


     

    1
    2
    String(false)        // returns "false"
    String(true)         // returns "true"
    cs




    3-3. Converting Dates to Strings

      전역 메소드 String()은 날짜 데이터를 문자열로 바꿔 줍니다.


     

    1
    String(Date())      // returns Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)
    cs




     

    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)

    [ 출처: W3Schools ]






    3-4. Converting Strings to Numbers

     전역 메소드 Number()는 문자열을 숫자로 변환합니다.


     숫자를 포함한 문자열("3.14")은 숫자(3.14)로 변환됩니다.


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


     

    1
    2
    3
    4
    Number("3.14")    // returns 3.14
    Number(" ")       // returns 0 
    Number("")        // returns 0
    Number("99 88")   // returns NaN
    cs



     

    MethodDescription
    parseFloat()Parses a string and returns a floating point number
    parseInt()Parses a string and returns an integer

    [ 출처: W3Schools ]





     

    4. The Unary + Operator

     단항 + 연산자(Unary + operator)는 변수를 숫자로 변환합니다.


     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    <!DOCTYPE html>
    <html>
        <body>
     
        <p>The typeof operator returns the type of a variable or expression.</p>
     
        <button onclick="myFunction()">Try it</button>
     
        <p id="demo"></p>
     
    <script>
    function myFunction() {
    var y = "5";
    var x = + y;
    document.getElementById("demo").innerHTML =
    typeof y + "<br>" + typeof x;
    }
    </script>
     
        </body>
    </html>
     
     
     
    cs



     

     



     변수가 변환되지 않는다면, 숫자로 되어 있지만, 값은 NaN 일 것입니다.


     

    1
    2
    var y = "John";   // y is a string
    var x = + y;      // x is a number (NaN)
    cs





    5. Converting Booleans to Numbers

      전역 메소드 Number()는 부울 값을 숫자로 변환합니다.



     

    1
    2
    Number(false)     // returns 0
    Number(true)      // returns 1
    cs




    6. Converting Dates to Numbers

       전역 메소드 Number()는 날짜 데이터를 숫자로 변환합니다.


     

    1
    2
    d = new Date();
    Number(d)          // returns 1404568027739
    cs



       날짜 메소드인 getTime() 또한 같습니다.


     

    1
    2
    d = new Date();
    d.getTime()        // returns 1404568027739
    cs







    7. Automatic Type Conversion

     자바스크립트가 잘못된 데이터 타입으로 작업을 시도 할 때, 올바른 타입의 값으로 변환을 해 줍니다.


     

    1
    2
    3
    4
    5
     
    5 + null    // returns 5         because null is converted to 0
    "5" + null  // returns "5null"   because null is converted to "null"
    "5" + 1     // returns "51"      because 1 is converted to "1"  
    "5" - 1     // returns 4         because "5" is converted to 5
    cs

     





    8. Automatic String Conversion

      자바스크립트는 객체나 변수의 출력을 하려 할 때, 자동으로 변수의 toString()을 호출하여 줍니다.


     

    1
    2
    3
    4
    5
    document.getElementById("demo").innerHTML = myVar;
     
    // if myVar = {name:"Fjohn"}  // toString converts to "[object Object]"
    // if myVar = [1,2,3,4]       // toString converts to "1,2,3,4"
    // if myVar = new Date()      // toString converts to "Fri Jul 18 2014 09:08:55 GMT+0200"
    cs

     



      숫자나 부울 값 또한 변환 됩니다.



     

    1
    2
    3
    // if myVar = 123             // toString converts to "123"
    // if myVar = true            // toString converts to "true"
    // if myVar = false           // toString converts to "false"
    cs


     


    댓글

Designed by Tistory.