Rules for JavaScript type conversion

Source: Internet
Author: User

Javascript variables are loose types. They can store any data types supported by JavaScript, and their variable types can be dynamically changed at runtime. See the example:

 
VaR n = 10; n = "Hello csser! "; N = {};

In the above example, first declare the N variable and initialize its value to 10 (integer type), then the string "Hello csser !" Assign a value to N, and then assign another object to it. The last n type is the object type. We can see that the type of Variable N is dynamic. In actual programming, we recommend that you do not change the type of the variable frequently, because this is not good for debugging.

Because the variable types in JavaScript are dynamicProgramIn actual execution, the concept of type conversion is required. Type conversion can be classified into implicit conversion and explicit conversion.
Explicit conversions are the automatic conversions performed by the program at runtime, while Explicit conversions are manually forced conversions of types. This article will summarize the type conversion of JavaScript.

Explicit Conversion

By manually performing type conversion, JavaScript provides the following Transformation functions:

Convert to numeric type: Number (MIX), parseint (string, Radix), parsefloat (string)
Convert to string type: tostring (Radix), string (MIX)
Convert to boolean type: Boolean (MIX)

1. Number (MIX) function, which can convert any type of parameter mix to numeric type.The rules are as follows:

    1. If it is a Boolean value, true and false are converted to 1 and 0 respectively.
    2. If it is a numeric value, return itself.
    3. If it is null, 0 is returned.
    4. If it is undefined, Nan is returned.
    5. If it is a string, follow the following rules:
      1. If the string contains only numbers, convert it to decimal (ignore leading 0)
      2. If the string contains a valid floating point format, convert it to a floating point value (ignore leading 0)
      3. If it is a Null String, convert it to 0
      4. If the string contains a non-preceding format, convert it to Nan
    6. If it is an object, call the valueof () method of the object and convert the returned value according to the previous rule. If the conversion result is Nan, The tostring () method of the object is called and the returned string value is converted again according to the preceding rules.

The following table lists the returned values of the valueof () object:

Object return value
array elements of the array are converted into strings separated by commas (,) and connected together. Its operations are the same as those of array. tostring and array. Join.
Boolean Boolean value.
date the storage time is the number of milliseconds in UTC that have elapsed since midnight, January 1, January 1, 1970.
function function itself.
Number numeric value.
Object the object itself. This is the default situation.
string string value.

Here are a few examples. Can you write out the correct results:

    • Number ("Hello csser !");
    • Number ("0 × 8 ″);
    • Number ("");
    • Number ("020dd ");
    • Number ("070 ″);
    • Number (true );

2. parseint (string, Radix) function, which converts a string to an integer value. It also has certain rules:

    1. Ignore the space before the string until the first non-null character is found.
    2. If the first character is not a numeric symbol or a negative number, Nan is returned.
    3. If the first character is a number, the parsing continues until the string is parsed or a non-numeric symbol is encountered.
    4. If the parsing result in the previous step starts with 0, it will be parsed as an octal component. If it starts with 0x, it will be parsed as a hexadecimal component.
    5. If the radix parameter is specified, the base is radix.

Quiz:

    • Parseint ("Hello csser !");
    • Number ("0 × 8 ″);
    • Parseint ("");
    • Parseint ("020dd ");
    • Parseint ("070 ″);
    • Parseint ("22.5 ″);

3. parsefloat (string) function, which converts a string to a value of the floating point type..

Its rules are basically the same as parseint, but there is also a difference: the first decimal point in the string is valid, and parsefloat ignores all leading 0, if a string contains a number that can be parsed as an integer, the return value is an integer instead of a floating point value.

4. tostring (Radix) method. All types of values except undefined and null have the tostring () method, which is used to return the string representation of the object..

Object Operation
Array Converts an array element to a string. The result string is separated by commas and connected.
Boolean If the Boolean value is true, "true" is returned ". Otherwise, "false" is returned ".
Date Returns the text representation of a date.
Error Returns a string containing the error message.
Function Returns a string in the following format, where functionname is the name of the tostring method function called:

Function functionname () {[native code]}

Number Returns the text representation of a number.
String Returns the value of a string object.
Default "[Object objectname]" is returned, where objectname is the object type name.

5. String (MIX) function, which converts any type of value to a string. The rule is:

    1. If the tostring () method exists, call this method (without passing the radix parameter) and return the result.
    2. If it is null, return "null"
    3. If it is undefined, return "undefined"

6. boolean (MIX) function, which converts any type of value to a Boolean Value.

The following values are converted to false: false, "", 0, Nan, null, and undefined. All other values are converted to true.

Implicit conversion

In some cases, JavaScript performs automatic type conversion even if we do not provide display conversion. The main situations include:

1. function used to check whether it is a non-numeric value: isnan (MIX)

Isnan () function, tested and found that this function will try to convert the parameter value with number (). If the result is "non-numeric", true is returned; otherwise, false is returned.

2. incrementing and decreasing Operators (including front and back) and unary plus/Negative Operators

These operators apply to values of any data type. For values of different types, the operators follow the following rules (the Rules are basically the same as those of number ):

    1. If a string contains valid numeric characters, convert it to a numeric value (the conversion rule is the same as number (). After adding or subtracting 1, the string variable is changed to a numeric variable.
    2. If it is a string that does not contain valid numeric characters, set the value of the variable to Nan and convert the string variable to a numeric variable.
    3. If it is a Boolean value of false, first convert it to 0 and then perform the operation of adding or subtracting 1, Boolean variable programming value variable.
    4. If it is a Boolean value of true, convert it to 1 first and then perform the operation of adding or subtracting 1. The Boolean value variable becomes a numerical variable.
    5. If it is a floating point value, add or subtract 1.
    6. If it is an object, first call the valueof () method of the object, and then apply the previous rule to the returned value. If the result is Nan, call the tostring () method and then apply the preceding rule. The object variable is a numeric variable.

Quiz:

What is the result of performing the post-increment operation on the following types of values?

"2", "02dd", "", false, 22.5, + "",-false, + new date ()

3. Addition Operators

The plus operator is also used for string connectors in Javascript, so the plus operator rules are divided into two situations:

    • If both operation values are numerical values, the rule is:
    1. If an operand is Nan, the result is Nan.
    2. If it is infinity + infinity, the result is infinity.
    3. If it is-infinity + (-infinity), the result is-infinity.
    4. If it is infinity + (-infinity), the result is Nan.
    5. If it is + 0 + (+ 0), the result is + 0
    6. If it is (-0) + (-0), the result is-0.
    7. If it is (+ 0) + (-0), the result is + 0
    • If an operation value is a string:
    1. If both operation values are strings, splice them.
    2. If only one operation value is a string, convert another operation value to a string and splice it.
    3. If an operand is an object, value, or Boolean value, call the tostring () method to obtain the string value, and then apply the preceding string rule. For undefined and null, call String () to explicitly convert them to strings.

It can be seen that in addition operations, if one operation value is of the string type, the other operation value is converted to a string and then connected.

4. multiplication, division, subtraction, and modulo Operators

These operators are intended for computation, so they are common: if one of the Operation values is not a numerical value, the number () function is implicitly called for conversion. For detailed rules for each operation, see definitions in ecmascript.

5. logical operators (! , &, |)

Non-logical (!) The operator first converts its operation value to a Boolean value through the Boolean () function, and then reverse it.

Logic and (&) operators. If an operation value is not a Boolean value, follow the following rules for conversion:

    1. If the first operand is converted to true by Boolean (), the second operation value is returned. Otherwise, the first operation value (not the converted value of Boolean () is returned)
    2. If one operation is null, null is returned.
    3. If an operation value is Nan, Nan is returned.
    4. If an operation value is undefined, undefined is returned.

Logical or (|) operator. If an operation value is not a Boolean value, follow the following rules:

    1. If the first operation value is converted to false by Boolean (), the second operation value is returned. Otherwise, the first operation value (not the value after Boolean () conversion) is returned)
    2. The processing rules and logic of undefined, null, and Nan are the same as those (&).

6. Relational operators (<, >,< =,> =)

Like the preceding operators, the Operation values of Relational operators can be of any type. Therefore, when using non-numeric types for comparison, implicit type conversion is also required:

    1. If both operation values are numerical values, compare the values.
    2. If both operation values are strings, the character encoding values corresponding to the strings are compared.
    3. If only one operation value is a value, convert the other operation value to a value for numerical comparison.
    4. If an operand is an object, call the valueof () method (if the object does not have the valueof () method, call the tostring () method). The result is compared according to the preceding rules.
    5. If an operation value is a Boolean value, convert it to a numerical value before comparison.

Note: Nan is a very special value, which is not equal to any type of value, including itself, and returns false if it is larger than any type of value.

7. Equal operator (=)

The equal operator implicitly converts the operation values and then compares them:

    1. If an operation value is a Boolean value, convert it to a value before comparison.
    2. If one operation value is a string and the other operation value is a numerical value, the number () function is used to convert the string to a numerical value.
    3. If one operation value is an object and the other is not, call the valueof () method of the object and compare the result according to the preceding rules.
    4. Null and undefined are equal.
    5. If an operation value is Nan, equal comparison returns false.
    6. If both operation values are objects, compare whether they point to the same object.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.