Home > Article > Web Front-end > Introduction to the role of double exclamation mark!! in JavaScript_javascript skills
!! Generally used to force the following expression into Boolean type data (boolean), that is, it can only be true or false;
I often see examples like this:
!! Generally used to force the following expression into Boolean type data (boolean), that is, it can only be true or false;
Because JavaScript is a weakly typed language (variables have no fixed data type), sometimes it needs to be cast to the corresponding type, similar to:
a=parseInt(“1234″) a=”1234″-0 //转换为数字 b=1234+”” //转换为字符串 c=someObject.toString() //将对象转换为字符串
Types 1 and 4 are explicit conversions, and types 2 and 3 are implicit conversions
Boolean conversion, the JavaScript convention is
false, undefined, null, 0, "" are false
true, 1, "somestring", [Object] is true
For null, undefined and other implicitly converted values, using the ! operator will produce a true result, so the purpose of using two exclamation marks is to convert these values into "equivalent" Boolean values;
Let’s take a look again:
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 are used, using one exclamation point returns true, and using two exclamation points returns false. Therefore, the role of two exclamation marks is that if the value of the variable is explicitly set ( Non-null/undified/0/"" and other values), the result will be returned based on the actual value of the variable. If it is not set, the result will return false.