Home  >  Article  >  Web Front-end  >  The role of two exclamation marks in JavaScript

The role of two exclamation marks in JavaScript

高洛峰
高洛峰Original
2016-11-28 10:49:131559browse

var a;

var b=!!a;

a defaults to undefined. !a is true, !!a is false, so the value of b is false, not undefined or other values, mainly to facilitate subsequent judgments.

!! Generally used to force the following expression to Boolean type data (boolean), which can only be true or false;

Because JavaScript is a weakly typed language (variables do not have a fixed data type) Sometimes it is necessary to cast to the corresponding type, similar to:

a=parseInt(“1234″)

a=”1234″-0 //Convert to number

b=1234+”” //Convert to character String

c=someObject.toString() //Convert the object to a string

The 1st and 4th are explicit conversions, 2 and 3 are implicit conversions

Boolean conversion, javascript convention rules For

false, undefined, null, 0, "" for false

true, 1, "somestring", [Object] for true

For null, undefined and other values ​​that are implicitly converted, when using the ! operator will produce true results, so the purpose of using two exclamation marks is to convert these values ​​into "equivalent" Boolean values;

====================== ================================================== =======================================

Let’s first explain with a simple example:
var o={flag:true};
var test=!!o.flag;//Equivalent to var test=o.flag||false;
alert(test);
Because the ! operator is used for null and undefined will produce a true result, so the purpose of using two exclamation marks is that if the value of flag in o is explicitly set (not null/undefined/0""/etc.), naturally test will be the same as o.flag The value; if not set, test will default to false, not null or undefined.
The classic example in jQuery is as follows: (jQuery 1.7.0.js: Line 748)
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 given If the third parameter 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