Data type conversions

Source: Internet
Author: User

Convert from a string value to a value

Usually we use functions to convert such as number (), parseint (), parsefloat ()

But we have to note that number () returns Nan if parsing a string that contains a non-numeric character. parseint () and parsefloat () ignore characters other than numbers. Returns Nan if there are only non-numeric characters in the string, or if the arguments are unreasonable.

In addition to using the relevant functions, we can also use implicit conversions. For example, using the operator "-", "*", "/", it is worth noting that "+" as a single-mesh operator can be implicitly converted (the argument is not reasonable when the return of Nan), but the binocular operator is a string connector.

If the return value is Nan, how to judge? Can be judged by the function isNaN (n).

Second, convert from numeric value to string

The method shown is n.tostring () or string (n)

The implicit approach is to use the binocular operator "+"

Three, convert to Boolean type

The Convert Boolean () is displayed, but we usually use implicit conversions.

The following values in the implicit conversion will be converted to false: numeric value 0, Nan value, null value, undefined value, empty string '

The more ingenious way is to use "!" A double negation. such as: !! 5

It should be noted that if we use the object type, we must be careful, even if it is an empty object, the return value is also true.

Iv. converting from object type to base data type

Convert to String: string (obj) is obj.tostring () "[Object Object]". This is also the case with implicit + '.

Convert to numeric value: Number (obj) is obj.valueof () if unable to convert, + (obj.tostring ())

Convert to Boolean: Boolean (obj) returns always True

Undefined value: NaN returns ' undefined '

V. Converting from a basic type to an object type

String--"string object, numeric Type-" Number object, Boolean--"Boolean object, Null value--" Error object, undefined value--"Error object

  

  

  

Data type conversions

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.