Often meet in JavaScript code!! , this article is to analyze the usage of 2 exclamation points in JavaScript in a more in-depth instance form. Share for everyone to use for reference. The specific analysis is as follows:
JavaScript in the!! Is the logical "not", that is, the logic "not" on the basis of "not" once again. Through! or!! You can convert many types to bool types and make other judgments.
First, the application scenario: to determine whether an object exists
Suppose you have such a JSON object:
{color: "#E3E3E3", "font-weight": "Bold"}
Need to judge whether exist, with!! That would be great.
If you simply print the object, you cannot determine whether it exists:
var temp = {color: "#A60000", "font-weight": "Bold"};
Alert (temp);
Result: [Object:object]
If you implement the JSON Object! or!!, you can tell if the JSON object exists:
var temp = {color: "#A60000", "font-weight": "Bold"};
alert (!temp);
Result: false
var temp = {color: "#A60000", "font-weight": "Bold"};
Alert (!! temp);
Result: True
Second, through! or!! The practice of converting various types into bool type
1. Null ' non ' returns true
var temp = null;
Alert (temp);
Result: null
var temp = null;
alert (!temp);
Result: True
var temp = null;
Alert (!! temp);
Result: false
2. Return true for undefined "non"
Result: undefined
Result: True
var temp;
Alert (!! temp);
Result: false
3. Return true to the "non" of an empty string
var temp= "";
Alert (temp);
Result: Empty
var temp= "";
alert (!temp);
Result: True
var temp= "";
Alert (!! temp);
Result: false
4. Return false to Non-zero integral type "non"
var temp=1;
Alert (temp);
Results: 1
var temp=1;
alert (!temp);
Result: false
var temp=1;
Alert (!! temp);
Result: True
5. Return true for 0 "non"
var temp = 0;
Alert (temp);
Results: 0
var temp = 0;
alert (!temp);
Result: True
var temp = 0;
Alert (!! temp);
Result: false
6. Return false to "non" of string
var temp= "AB";
Alert (temp);
Result: AB
var temp= "AB";
alert (!temp);
Result: false
var temp= "AB";
Alert (!! temp);
Result: True
7. Return FALSE for "non" of array
var temp=[1,2];
Alert (temp);
Result: 1,2
var temp=[1,2];
alert (!temp);
Result: false
var temp=[1,2];
Alert (!! temp);
Result: True
It is believed that this article has some reference value for the learning of JavaScript programming.