Summary of data type conversions in JavaScript

Source: Internet
Author: User

Summary of data type conversions in JavaScript

In JS, data type conversions are divided into explicit data type conversions and implicit data type conversions.

1, explicit data-type conversions

A: Turn numbers:

1) Number conversion:

Code:

var a = "123";

A = number (a);

Attention:

A) If the converted content itself is a string of numeric type, it will return itself in the future at the time of conversion.

b) If the converted content itself is not a string of numeric type, then the result is Nan at the time of conversion.

c) If the content to be converted is an empty string, that with the result of the conversion is 0.

D) If it is a different character, the result will be nan at the time of conversion.

2) parseint ():

Code:

var a = "123"; A = parseint (a);

A) ignore the whitespace in front of the string until the first non-null character is found, and the non-numeric string followed by the number is removed.

b) If the first character is not a number sign or minus sign, return Nan

c) The decimal is rounded. (Rounded down)

3) parsefloat ();//floating-point number (decimal)

As with parseint, the only difference is that parsefloat can keep decimals.

B. Transfer string

Other data types can be converted to strings.

1) String ():

Code:

var a = 123;

A = String (a);

2). ToString () method to convert (wrapper class).

Code:

var a = 123; A = A.tostring ();

Undefined,null cannot use ToString.

C. Go to the Boolean type:

Other types can be converted to a Boolean value:

Boolean ():

Code:

var a = "true"; A = Boolean (a);

Note: All content is true after conversion for a Boolean conversion except: false, "" (empty string), 0, NaN, undefined

2, implicit conversion

A) Turn number:

var a = "123";

A = +a;

Subtraction and the remainder of the string can be implicitly converted to number.

b) Turn string:

var a = 123;

A = a + "";

c) Turn to Boolean:

var a = 123;

A =!! A

Summary of 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.