The role of two exclamation points in JavaScript explains _javascript skills

Source: Internet
Author: User
Let's use a simple example to illustrate:
Copy Code code as follows:

var o={flag:true};
var test=!! o.flag;//equivalent to Var test=o.flag| | False
alert (test);

Because null and undefined use the! operator to produce true results, the effect of using two exclamation points is that if you explicitly set the value of flag in O (not null/undefined/0 ""/equivalent), The natural test takes the same value as O.flag, and if not set, the test defaults to false instead of null or undefined.
Some of the more classic examples in jquery are as follows: (jquery 1.7.0.js:line 748)
Copy Code code as follows:

Grep:function (Elems, callback, inv) {
var ret = [], retVal;
INV =!! Inv

Go through the array, only saving the items
This pass the validator function
for (var i = 0, length = elems.length i < length; i++) {
RetVal =!! Callback (elems[i], i);
if (Inv!== retVal) {
Ret.push (elems[i]);
}
}

return ret;
}

When using the grep function, if the third argument is given and is not null/undefined/0 ""/equivalent, the INV is true or false. The purpose of this is to ensure that the values of inv and retval can only be taken in true/false, not other values, to facilitate subsequent judgment.

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.