日期:2014-05-16  浏览次数:20435 次

JavaScript ---- Type Conversions
JavaScript is very flexible about the types of values it requires.
When JavaScript expects a boolean value, you may supply a value of any type, and JavaScript will convert it as needed.
If JavaScript wants a string, it will convert whatever value you give it to a string.
If JavaScript wants a number, it will try to convert the value you give it to a number(or to NaN if it cannot perform a meaningful conversion).
例如:
     10 + " objects"         // => "10 objects". Number 10 converts to a string
     "7" * "4"               // => 28: both strings convert to numbers
     var n = 1 - "x";        // => NaN: string "x" can't convert to a number
     n + " objects"          // => "NaN objects": NaN converts to string "NaN"

显式转换:
    显式转换最简单的方式是使用:Boolean(), Number(), String(), or Object() functions.
    例如:
         Number("3")                 // => 3
         String(false)               // => "false" or use false.toString()
         Boolean([])                 // => true
         Object(3)                   // => new Number(3)

The toString() method defined by the Number class accepts an optional argument that specifies a radix, or base, for the conversion. If you do not specify the argument, the  conversion is done in base 10. However, you can also convert numbers in other bases (between 2 and 36).
例如:
     var n = 17;
     binary_string = n.toString(2);        // Evaluates to "10001"
     octal_string = "0" + n.toString(8);   // Evaluates to "021"
     hex_string = "0x" + n.toString(16);   // Evaluates to "0x11"

数值处理:
    Number(): If you pass a string to the Number() conversion function, it attempts to parse that string as an integer or floating-point literal. That function only works for base-10 integers, and does not allow trailing characters that are not part of the literal.
    parseInt():
    parseFloat(): The parseInt() and parseFloat() functions (these are global functions, not methods of any class) are more flexible.
    parseInt() parses only integers
    parseFloat() prases both integers and floating-point numbers
    If a string begins with "0x" or "0X", parseInt() interprets it as a hexadecimal number. Both parseInt() and parseFloat() skip leading whitespace, parse as many numeric characters as they can, and ignore anything that follows.If the first nonspace character is not part of a valid numeric literal, they return NaN:
    例如:
       
        parseInt("3 blind mice")       // => 3
        parseFloat(" 3.14 meters")     // => 3.14
        parseInt("-12.34")             // => -12
        parseInt("0xFF")               // => 255
        parseFloat(".1")               // => 0.1
        parseInt("0.1")