首页 > 编程语言 > 详细

What is the !! (not not) operator in JavaScript?

时间:2019-07-04 19:42:52      阅读:91      评论:0      收藏:0      [点我收藏+]

What is the !! (not not) operator in JavaScript?

解答1

Coerces强制 oObject to boolean. If it was falsey (e.g. 0, nullundefined, etc.), it will be false, otherwise, true.

!oObject  //Inverted boolean
!!oObject //Non inverted boolean so true boolean representation

So !! is not an operator, it‘s just the ! operator twice.

Real World Example "Test IE version":

let isIE8 = false;  
isIE8 = !! navigator.userAgent.match(/MSIE 8.0/);  
console.log(isIE8); // returns true or false 

If you ⇒

console.log(navigator.userAgent.match(/MSIE 8.0/));  
// returns either an Array or null  

but if you ⇒

console.log(!!navigator.userAgent.match(/MSIE 8.0/));  
// returns either true or false


It converts a nonboolean to an inverted boolean (for instance, !5 would be false, since 5 is a non-false value in JS), then boolean-inverts that so you get the original value as a boolean (so !!5 would be true).

 

解答2

! is "boolean not", which essentially typecasts the value of "enable" to its boolean opposite.

The second ! flips this value.

So, !!enable means "not not enable," giving you the value of enable as a boolean.

 

What is the !! (not not) operator in JavaScript?

原文:https://www.cnblogs.com/chucklu/p/11133975.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!