Data type conversions in JavaScript

Source: Internet
Author: User

The "original values" mentioned in this article refer to undefined,null,boolean,string and number.

The objects in this article are native objects, which are converted by the host objects (browser-defined objects) according to their respective algorithms.

JavaScript has six types of data, Undefined, Null, Boolean, number, string, and object.

With regard to type conversion, JavaScript is interesting in that it automatically casts the type based on the type of data he expects . That is, even if you do not give him what he wants, he will do it himself and turn you into what he wants.

Then there are two problems here, What does he expect?and his How to change。 Let's look first. How did he change?  We know that JavaScript has functions for type conversion, such as String (), number (), Boolean (), Object (). Through these methods, we can an explicitTo convert the data to the desired type. Is the result of the conversion of various data types to each other in the JavaScript authoritative guide:

The conversion of the original value is simple, almost identical to what we imagined, which is complicated by the conversion of the object to the original value, so it is discussed separately.

3.8.3 describes the process of converting objects to different types, regardless of the type to be converted, by calling JavaScript to use the object's two conversion methods--valueof () and ToString () to get the original value, and get the result as follows:

Simply converting to different types gets the original value rule differently.

    • Rules for converting an object to a string:
    1. If he has ToString (), call, if he returns a primitive value, convert it to a string (if not a string) and return it.
    2. If he returns not the original value, or if he does not have ToString (), call valueof (), if return a raw value, convert it to a string (if not a string) and return.
    3. Otherwise, a type error exception is thrown.
    • To convert an object to a number rule:
    1. Try using valueof () First, if you return a primitive value, and then convert it to a number and return it.
    2. If the return is not of the original value or if he does not have valueof (), then try ToString (), if a primitive value is returned, convert it to a number and return.
    3. Otherwise, a type error exception is thrown.
These are the rules for explicit conversion of data types. As we said before, JavaScript will do the data according to its own needs. Implicit conversions。 That's what you need to know, What does he expect? That is, when he will make an implicit conversion of this behavior.
    • When it executes "!" operator and if statement, it will expect a Boolean value, and if you give him a Boolean value, he will call Boolean () in the background to convert its operands to a Boolean value.
So !! X is equivalent to a Boolean (x)
    • When it executes a "-" or a unary "+" operator, it expects one or two values, and if you give him a value that is not a number, he will call number () in the background to convert its operand to a numeric value.
So x-0 is equivalent to number (x)+x is equivalent to number (x)
    • When it executes a two-dollar "+", "= =" ("! ="), and the relational operator, the type is converted according to its own expectations.
And no matter what they expect, one thing is the same, is that when they encounter an object, they convert the object to the original value and return it directly as a result ., and then type conversions based on their expectations.                     The rules that return the original values are: Non-date objects first try to call valueof (), no longer call ToString (), and the Date object calls ToString (). Then we can look at their respective expectations:two USD "+", expecting a number or string, the most expected string, other types will be type conversions. That is, whenever one is a string, he expects the string and then calls string () to convert the non-string to a string.                       If two is not a string, he will call number () to convert two operands to a numeric value.                               If one is an object, it is converted to the original value, and then compared to another operand, determines how to act. So x+ "" is equivalent to string (x)。Relational operators ("<", ">", "<=", ">="), expect numbers and strings, most expect numeric values, and other types of operands will be type-converted:If the operand is an object, it is converted to the original value. (Call valueof (except the Date object) to return the result directly, not cast to a number or string.) After the conversion, if it is a string, then in alphabetical order, if at least one is not a string, then two operands will be converted to numeric values for comparison.rules for "= =" (" ! ="):1. The same type is compared according to the rule = = =.                              2. Different types of: ①undefined==null② strings and Numbers, converts a string to a number.                              ③ A Boolean value and a number to convert the Boolean value to a number. ④ If one value is an object and the other is a number or a string. Converts the object to the original value.                              Objects in non-JavaScript cores are converted to original values through the methods defined in their implementations.  ⑤ other different types of comparisons are not equal. Using this knowledge, we can understand how some concise code achieves its purpose:
    • +date returns the number of milliseconds that represents a date (date is a DateTime object.) )
Because + converts the operand to a number, and date is an object, the object's valueof () method is called first, and this method of the Date object returns the number of milliseconds representing the date.
    • The IF (-[1,]) value in non-IE6/7/8 is true and false in IE6/7/8.
The first step is to execute "-". Because the "-" operator converts the operand to a numeric value, the array is an object, calls its ValueOf method, returns an object, and continues to call its ToString () method, the non-IE6/7/8 JS engine automatically strips the last comma of the array, so the result is [1],[1] is converted to a numeric value, which is 1, and the IE6/7/8 JS engine does not automatically reject the last comma in the array, so its valueof return value is "1," which is converted to a number to get Nan, and the second step is to execute the IF statement. The IF statement expects a Boolean value that converts-1 to a Boolean value of true.  Convert (-nan) to Boolean worthwhile to false. This feature of JavaScript is very flexible and can be used to reduce a lot of code. However, there are pros and cons, if we do not understand its operating mechanism, it is likely to be accidentally caught in the hole. So when we write code, we must pay attention to its implicit conversion behavior. These are some of my understanding and summary, there may be some mistakes in the place, I hope you can help me correct.

Data type conversions in JavaScript

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.