Data type review-data type conversion (explicit and implicit)-js Learning Note 2015-6-3 (47th day)

Source: Internet
Author: User
Tags string methods

For JS this language, because it is a dynamic type language, the variable is no type, can be given any value at any time.

However, the data itself and the various operations are typed, so the variable needs to be converted to the type of operation.

In most cases, this type of data conversion is automatic, but it sometimes requires a manual cast.

First look at coercion type conversions (explicit)

The previously mentioned Namber, parseint, parsefloat are mandatory type conversions;

Here is looking at Ruan Yi Feng blog (http://javascript.ruanyifeng.com/grammar/conversion.html#toc1)

the conversion of the number method , where the next record is made:

(1) Conversion rules for primitive type values

    • Value: Converted or original.

    • String: If it can be resolved to a numeric value, it is converted to the corresponding numeric value, otherwise Nan is obtained. The empty string is converted to 0.

    • Boolean value: True turns into 1,false to 0.

    • Undefined: Turns into Nan.

    • Null: Turn into 0.

(2) Conversion rules for objects

The translation rules for objects are more complex.

    1. The valueof method of the object itself is called first, and if the method returns the value of the original type (numeric, String, and Boolean), the number method is used directly on the value and no further steps are made.

    2. If the ValueOf method returns the value of a composite type, and then calls the ToString method of the object itself, if the ToString method returns the value of the original type, the number method is used for that value and no further steps are made.

    3. If the ToString method returns a value of a composite type, an error is returned.

Also mentioned are 2 kinds of wonderful taste of the classroom teacher did not mention the method:

String function: Cast to String

(1) Conversion rules for primitive type values

    • Value: to the appropriate string.

    • String: The converted or original value.

    • Boolean value: True to "true", false to "false".

    • Undefined: Switch to "undefined".

    • Null: to "null"

(2) Conversion rules for objects

If you want to convert an object to a string, the following steps are taken.

    1. The ToString method is called first, and if the ToString method returns a value of the original type, the string method is used for the value, and the following steps are no longer performed.

    2. If the ToString method returns a value of a composite type, and then calls the ValueOf method, if the ValueOf method returns a value of the original type, the string method is used for the value, and the following steps are no longer performed.

    3. If the ValueOf method returns a value of a composite type, an error is returned.

This process of the string method is exactly the opposite of the number method

And Mr. Nguyen also mentioned that Boolean conversion

Boolean function: Cast to Boolean

(1) Conversion method of primitive type value

The conversion result for the following six values is false, and the other values are all true.

    • Undefined
    • Null
    • -0
    • +0
    • NaN
    • "(empty string)

(2) Conversion rules for objects

The Boolean value of all objects is true, and even the Boolean object that corresponds to False is true.

Boolean(new Boolean(false))// true

Note that the empty object {} and the empty array [] are also turned to true.

Boolean([]) // trueBoolean({}) // true




The following is an implicit type conversion, or (JS internal automatic conversion)
So when does an implicit type conversion occur?

JavaScript automatically converts the data type when it encounters the following conditions:

    • Different types of data are calculated by each other;

    • Boolean value for data of non-Boolean value type;

    • Use unary operators (that is, "+" and "-") for data of non-numeric types.

First the wonderful teacher mentioned the centralized implicit type conversion situation:

Implicitly-Typed conversions:
+ 200 + ' 3 ' into a string
-*/% ' 200 '-3 becomes digital
+ +--Become a digital
Comparison of > < numbers, Comparison of strings
Take the inverse and turn the data type on the right to a Boolean value.
==

Alert (number (' ... ')); NaN
Alert (' ... '-9); NaN


Nan is returned when a data type conversion fails;

Alert (' 2 ' = = 2);

Alert (' >9 ') returns True, this is a comparison of numbers
Alert (' 10000000 ' > ' 9 '); Returns FALSE, which is the comparison of the strings, compared with the encoding of the two;
> < is a comparison of numbers and strings

Alert (! ') Ok '); This time returns false, why?
After reading the JS tutorial of Nanyi, I realized that the system would automatically call the internal Boolean method to convert where expected to be a Boolean value.
The Boolean method can convert any type of variable to a Boolean value

Another thing to mention is the + operator,

There is a, a string in the case of an operation//two operators, as long as one is a string, then the other regardless of what type, will be automatically converted to a string, and then perform a string join operation

B, two operators are numeric or Boolean values//In this case, the addition operation is performed, the Boolean value is converted to a value (True is 1,false is 0)

C, there are objects in the operator

If an object exists (or, to be exact, a value of a non-primitive type), the ValueOf method of the object is called first. If the return result is a value of the original type, the above two rules are applied; otherwise, the ToString method of the object is invoked, and the two rules above are applied to its return value. (This piece is not understood at the moment, after learning the object and then carefully study)

About numeric conversions of two equals signs :

See Masaki's Blog: http://www.cnblogs.com/rubylouvre/p/3990290.html
In addition, in order to avoid this problem, most companies may require that the use of the double equals sign, directly using the three equals sign is good
/*
The implicit type conversion, which is said here, is the conversion caused by = =.

Returns False if there is a Nan
And see if there's a Boolean, and Boolean converts the Boolean to a number.
Then see if there are no strings, there are three cases, the other is the object, the object is converted using ToString, the other is the number, the string to the number, the other side is a string, direct comparison;
If it is a number, the object is the object, the objects are compared with valueof, and the others return false.
Null, undefined does not perform type conversions, but they are both equal
This order must be remembered, which is often asked during the interview.

Here are some miscellaneous questions, do it yourself

0 = = undefined//False

1 = = TRUE//True

2 = = {Valueof:function () {return 2}}//True

Nan = = nan//False

8 = = undefined//False

1 = = undefined//False

Null = = {Tostring:function () {return 2}}//False

0 = = NULL//False

NULL = = 1//False



{tostring:function () {return 1}, Valueof:function () {return []}} = = 1

*/

and Mu-class teacher ppt (to help understand):

Because of the implicit conversion of data types, according to Mr. Ruan's advice is:

Because of the great uncertainty of automatic conversions and the difficulty of debugging, it is recommended that you explicitly convert all Boolean, number, and string methods where expected to be booleans, values, and strings

On the addition and subtraction of symbols, Mu-class network "in layman's JavaScript" also mentioned

Using this implicit conversion feature, if we want to convert the data type of that variable to a number, then num-0; At this point the NUM is implicitly converted into a number;

Similarly, to convert a variable's data type to a string, then num + '; Variable plus an empty string, num is converted to a string

var typeof (num + ")" string "vartypeof(num-0)" number "

Written at the end:

Tips: Through the comparison of the good taste of the classroom video and some of the online tutorials (personal blog, Ruan a peak, Masaki, etc.) found that all the data type conversion is not all the case, all in the learning JS, but also need to see their own, more hands-on, so that more accurate and deep understanding.

Data type review-data type conversion (explicit and implicit)-js Learning Note 2015-6-3 (47th day)

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.