2015-11-03 100 views
0

刚刚看到一段javascript代码,他们在变量前面放置了两个感叹号,我不确定它的作用。我知道在变量前面做了什么,而不是第二个做什么。任何想法将不胜感激。在javascript中使用感叹号

回答

-3

来源:http://brianflove.com/2014/09/02/whats-the-double-exclamation-mark-for-in-javascript/

function() { 
    var nothing = ""; 
    if (nothing) { 
     window.alert('Nothing'); 
    } else { 
     window.alert('Huh?'); 
    } 
} 
When the function above is executed we will get the alert “Huh?” because the value of the variable hello is being evaluated to be false. This is what is commonly referred to as truthy versus falsey. 

The following values are considered by JavaScript to be falseys: 

Empty string: “” 
0 
null 
undefined 
NaN 
The following values are considered by JavaScript to be truthys: 

Object: {} 
Array: [] 
Not empty string: “anything” 
Number other than zero: 3.14 
Date: new Date(); 
The JavaScript engine that is executing your code will attempt to convert (or coerce) a value to a boolean when necessary, such as when evaluated in an if-statement.  

So, why double exclamation marks? 

In some cases you may want to cast a variable to be explicitly boolean. Why? Well, the number one reason is that most of time developers do not use type safe comparison operators. 

The type safe comparison operators are: 

Strictly equal: === 
Strictly unequal: !== 
When using the type safe comparison operators you are both checking that the values are equal (or unequal) and that their type is the same. Without the type safe comparison operators, you are allowing the JavaScript engine the freedom to coerce your variables to true or false based on the truthy/falsey logic. 

To cast your JavaScript variables to boolean, simply use two exclamation signs: 

function() { 
    var name = "Brian"; 

    //alert 'string' 
    window.alert(typeof name); 

    //cast to boolean 
    var bool = !!name; 

    //alert 'boolean' 
    window.alert(typeof bool); 
} 
In the example code above we are casting the string “Brian” to a boolean value. Therefore the second alert will indicate that the variable is now a boolean value.