Home  >  Article  >  Web Front-end  >  Introduction to the role of double exclamation mark!! in JavaScript_javascript skills

Introduction to the role of double exclamation mark!! in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:35:491176browse

!! 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:

Copy code The code is as follows:

var a;
var b=!!a;

a defaults to undefined. !a is true, !!a is false, so the value of b is false, not undefined or other values, mainly to facilitate subsequent judgments.

!! 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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn