Using javascript: how to convert other types of values to boolean values

Source: Internet
Author: User

1.Convert using a Boolean object

Copy codeThe Code is 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, First '! 'Convert the value to a Boolean value and take the non-value of the value. The second value '! 'Restore its Boolean value, similar to the principle of "negative Positive.

Copy codeThe Code is 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 result obtained is the same as method 1.

Finally, you need to know: Any javascript value can be converted to a Boolean value. The following values are converted to false:

Copy codeThe Code is as follows: undefined, null, 0,-0, NaN, "// null String

Note:The '0' string that only contains 0 will be converted to true!

Add the special characteristics of null and undefined:

Copy codeThe Code is 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.