Home > Web Front-end > JS Tutorial > 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
Release: 2016-05-16 17:57:57
Original
1365 people have browsed it

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.
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template