Using javascript: A workaround for converting other type values to Boolean type values _javascript tips

Source: Internet
Author: User

1. convert using a Boolean object

Copy Code code as follows:

var num123 = 123, str = ' abc ', o = {name: ' Test '}, NUM0 = 0; num123 = Boolean (num123); True NUM0 = Boolean (NUM0); False str = Boolean (str); True o = Boolean (o); True

2. use two '! ' operator, the first '! ' Converts a value to a Boolean value and takes a value that is not a value, the second '! ' Restore its Boolean value, similar to the "negative negative positive" principle.

Copy Code code as follows:

var num123 = 123, str = ' abc ', o = {name: ' Test '}, NUM0 = 0; num123 =!! (num123); True NUM0 =!! (NUM0); False str =!! (str); True o =!! (o); True

The results obtained are the same as Method 1.

Finally, you should know that any JavaScript value can be converted to a Boolean value. The following values are converted to false:

Copy Code code as follows:

Undefined,null,0,-0,nan, ""//empty string

need to be awareIs ' 0 ', which contains only 0 of the strings that turn into true!.

Add the specificity of null and undefined:

Copy Code code as follows:

Null = = undefined//true null = = undefined//false

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.