Type conversion in JavaScript (i)

Source: Internet
Author: User

  • Objective

    JavaScript is a very flexible and weakly typed language, and its flexibility is reflected in its varied and diverse types of conversions. For example, when JavaScript expects to use a Boolean value (such as an if statement) you can provide any type of value, JavaScript will convert the type as needed, and when you use the = = operator to compare two types of values, the two operands are converted as needed. The same thing happens when you use operators such as +,> and <. These flexible and complex conversions tend to overwhelm beginners, and this article summarizes the type conversion of JavaScript.

  • Classification of types in JavaScript

    The types in JavaScript can be divided into two main classes: primitive type (primitive types) and object type (objects types). Where the original type consists of the number numbers, string strings, Boolean Boolean, Null and undefined five, except for these five types are object types (including Function,array,regex, etc.).

  • Conversion of primitive types to other types

    The conversion between different types of values in JavaScript is shown in the following table (the table is <javascript authoritative Guide > Chapter III, Table 3-2)

    Value String Digital Boolean value Object
    Undefined "Undefined" NaN False Throws TypeError
    Null "NULL" 0 False Throws TypeError
    True "True" 1 New Boolean (True)
    False "False" 0 New Boolean (FALSE)
    "" (empty string) 0 False New String ("")
    "1.2" 1.2 True New String ("1.2")
    "One" NaN True New String ("one")
    0 "0" False New Number (0)
    -0 "0" False New number (-0)
    NaN "NaN" False New Number (NaN)
    Infinity "Infinity" True New Number (Infinity)
    -infinity "-infinity" True New Number (-infinity)
    1 (Other non-infinity numbers) "1" True New Number (1)
    {} Pending discussion Pending discussion True
    [] “” 0 True
    [9] "9" 9 True
    [' A '] Use the Join () method to concatenate individual elements with a comma delimiter NaN True
    function () {} Pending discussion NaN True
    As
    can be seen from the table above, the type conversion between primitive types in JavaScript has been clearly defined, the conversion of the original type to the object is also well defined, and the table has three "pending" cells, all of which are conversions between the object type and the original type. Is the difficulty of JavaScript type conversion. Here is a brief summary of the first two scenarios:
    • Only undefined,null, empty strings, 0 (including 0 and-0), and Nan to Boolean types are converted to false, and the values of the remaining types are converted to Boolean types that are true
    • Conversions of primitive types to object types, null and undefined throw exceptions, and number,string and bool are converted to the corresponding wrapper type Number,string,boolean. For these three primitive types, You can also use the object constructor to convert to objects, and the object constructor calls Number,string or one of the Boolean to construct the objects based on the specific values of the passed parameters. The code is as follows
      varnum =NewNumber (10);varstr =NewString ("ABC");var Boolean=NewBoolean (false);varNUM1 =NewObject (10);varSTR1 =NewObject ("ABC");varBoolean1 =NewBoolean (false); Console.log (typeofnum + "" +num.constructor);//Output Object function number () {[native code]}Console.log (typeofSTR + "" + str.constructor);//Output Object function String () {[native code]}Console.log (typeof Boolean+ " " +Boolean. constructor);//Output Object function Boolean () {[native code]}Console.log (typeofNUM1 + "" + num1.constructor);//Output Object function number () {[native code]}Console.log (typeofSTR1 + "" + str1.constructor);//Output Object function String () {[native code]}Console.log (typeofBoolean1 + "" + boolean1.constructor);//Output Object function Boolean () {[native code]}
Conversion of the object type to the original type

The "object type" mentioned in this section refers only to native objects, which can be understood as a programmer-defined object type and does not include objects defined by a JavaScript host (such as a browser). Because the host-defined object may have special methods for type conversion. In addition, the original type in this section header contains only bool,string and number three types. Object-to-null or undefined conversions do not need to be discussed. The conversion of the object to the bool type has been discussed above, and all object type conversion Boolean types are true, even if new Boolean (false) Converting to Boolean type is also true. So what is worth discussing in this section is the conversion of the object type to the string and the conversion of the object type to the number.

The conversion of object-to-string and object-to-number types involves two important methods, and the resulting conversion results are affected by the results returned by both methods. These two methods are ToString and valueof. All objects inherit from object objects to both methods. The ToString method is used to return the string representation of an object (but in fact it is also possible to return a string). The ToString method, which inherits from object by default, does not return much meaningful content. The ValueOf method is intended to return an original type value that can represent an object, but because of the complexity of the object, in most cases it is not possible to represent it with a primitive type value. So the default valueof just returns the object itself. The date type is a special case, which is the only type of JavaScript predefined type that overrides the ToString and valueof methods.

The object type conversion string type step is as follows:

    1. If the object has the ToString method, the ToString method is called, and if the return is a primitive type, the original type is converted to a string (of course, if ToString returns the string it is not required)
    2. If the object does not have the ToString method, or if ToString is not returning the original type, try calling the ValueOf method, and if the ValueOf method returns the original type, the original type is converted to a string (if the string is not needed if valueof is put back)
    3. Throws a TypeError exception if neither the ToString method nor the ValueOf method exists, or if their return type is not the original type

The object type conversion number type step is as follows:

    1. If the object has a valueof method and the method returns an original type, the original type is converted to a number
    2. Otherwise, if the object has the ToString method and the method returns the original type, the original type is converted to a number
    3. Otherwise throws TypeError exception

The

example is similar to the object conversion string and is no longer given. Here, you should know why an empty array is converted to a string that is an empty string, but converted to a number of 0. You can interpret the result of an array of only one element when converted to strings and numbers.

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.