Home > Article > Web Front-end > Detailed interpretation of the !! symbol problem in JS
!! Generally used to force the following expression to Boolean type data (boolean), that is, it can only be true or false. Let’s take a look at the !! in JS introduced to you through this article. Friends who need it can refer to it
!! is generally used to force the following expressions into Boolean type data (boolean), that is Can only be true or false.
var a; var b=!!a;
aThe default is undefined. !a is true, !!a is false, so the value of b is false, not undefined or other values, mainly to facilitate subsequent judgments.
Because JavaScript is a weakly typed language (variables have no fixed data type), sometimes it needs to be forced to the corresponding type, similar to:
a=parseInt(“1234″) a=”1234″-0 //转换为数字 b=1234+”” //转换为字符串 c=someObject.toString() //将对象转换为字符串
The first and fourth types is explicit conversion, 2 and 3 are implicit conversion
Boolean conversion, the javascript convention rules are
false, undefined, null, 0, "" are false
true, 1, "somestring", [Object] is true
for null, undefined and others When using implicitly converted values, the ! operator will produce a true result, so the function of using two exclamation marks is to convert these values into "equivalent" Boolean values;
var foo; alert(!foo);//undifined情况下,一个感叹号返回的是true; alert(!goo);//null情况下,一个感叹号返回的也是true; var o={flag:true}; var test=!!o.flag;//等效于var test=o.flag||false; alert(test);
This example , demonstrates that when undiffed and null, using one exclamation point returns true, using two exclamation points returns false, so the role of two exclamation points is that if the value of the variable is explicitly set (not null/undiffed/0 /" "equal value), the result will be returned based on the actual value of the variable. If it is not set, the result will return false.
"!!" in JS
var o={flag:true}; var test=!!o.flag;//等效于var test=o.flag||false; alert(test);
Since 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 flag in o is explicitly set (not null/undefined/0""/etc.), naturally the test will follow o .flag has the same value;
If not set, test will default to false, not null or undefined.
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to implement singleton mode using ES6
##How to create a child process using node.js (detailed tutorial)
How to use slider to set data values in WeChat mini program
How to implement pop-up bottom menu in WeChat mini program
The above is the detailed content of Detailed interpretation of the !! symbol problem in JS. For more information, please follow other related articles on the PHP Chinese website!