The role of two exclamation marks in js

!! in javascript is a logical "non-not", that is, "not" again on the basis of the logical "not". Through ! or !!, many types can be converted to bool types, and then other judgments can be made.

 Common example, not of empty string is true

console.log(
  !true,         //false
  !false,        //true
  !0,            //true
  !'',           //true
  ![],           //false
  !null,         //true
  !undefined,    //true
  !{},           //false
)

 

1. Application scenario: determine whether an object exists

Suppose there is such a json object:

{ color: "#E3E3E3", "font-weight": "bold" }

Need to judge whether it exists, use!! is better.

If you just print the object, you can't tell if it exists:

var temp = { color: "#A60000", "font-weight": "bold" };
alert(temp);

Result: [object: Object]

If you implement ! or !! on the json object, you can determine whether 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

2. The convention of converting various types to bool types through ! or !!

1. Return true for "not" of null

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 "not" of undefined

var temp;
alert(temp);

result: undefined

var temp;
alert(!temp);

result: true

var temp;
alert(!!temp);

result: false

3. Return true for "not" of empty string

var temp="";
alert(temp);

result: empty

var temp="";
alert(!temp);

result: true

var temp="";
alert(!!temp);

result: false

4. Return false for "not" of non-zero integers

var temp=1;
alert(temp);

Result: 1

var temp=1;
alert(!temp);

result: false

var temp=1;
alert(!!temp);

result: true

5. Return true for "not" of 0

var temp = 0;
alert(temp);

Result: 0

var temp = 0;
alert(!temp);

result: true

var temp = 0;
alert(!!temp);

result: false

6. Return false for "not" 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 "not" of an 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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324465794&siteId=291194637