Home  >  Article  >  Web Front-end  >  Explanation of the function of two exclamation marks in JavaScript_javascript skills

Explanation of the function of two exclamation marks in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:57:571335browse

Let’s use a simple example to illustrate:

Copy code The code is as follows:

var o={ flag:true};
var test=!!o.flag;//Equivalent to var test=o.flag||false;
alert(test);

Due to Using the ! operator on null and undefined will produce a true result, so the purpose of using two exclamation marks is that if the value of the flag in o is explicitly set (not null/undefined/0""/etc.), the natural test It will take the same value as o.flag; if not set, test will default to false instead of null or undefined.
The classic example in jQuery is 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
// that 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 parameter is given and is not null/undefined/0""/, then inv is true, otherwise it is false. The purpose of this is to ensure that the values ​​​​of inv and retVal can only be taken from true/false, not other values, to facilitate subsequent judgments.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn