我看到一些代码似乎使用了我不认识的运算符,以两个感叹号的形式,像这样:!!。有人能告诉我这个接线员做什么吗?
我看到这件事的背景是,
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
我看到一些代码似乎使用了我不认识的运算符,以两个感叹号的形式,像这样:!!。有人能告诉我这个接线员做什么吗?
我看到这件事的背景是,
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
当前回答
a = 1;
alert(!a) // -> false : a is not not defined
alert(!!a) // -> true : a is not not defined
对于a、 它检查a是否未定义,而!!a检查变量是否已定义。
!!a与相同!(!a)。如果定义了a,则a为真!a是假的,而且!!a为真。
其他回答
看来是!!运算符导致双重否定。
var foo = "Hello, World!";
!foo // Result: false
!!foo // Result: true
以下是AngularJS的一段代码:
var requestAnimationFrame = $window.requestAnimationFrame ||
$window.webkitRequestAnimationFrame ||
$window.mozRequestAnimationFrame;
var rafSupported = !!requestAnimationFrame;
他们的意图是根据requestAnimationFrame中函数的可用性将rafSupported设置为true或false。
通常可以通过以下方式进行检查:
if(typeof requestAnimationFrame === 'function')
rafSupported =true;
else
rafSupported =false;
这条短路可以用!!
rafSupported = !!requestAnimationFrame;
因此,如果requestAnimationFrame被分配了一个函数,那么!requestAnimationFrame将为false,还有一个!这是真的。
如果requestAnimationFrame未定义,则!requestAnimationFrame将是真的,还有一个!这将是错误的。
这只是逻辑NOT运算符,两次。它用于将某些内容转换为布尔值,例如:
true === !!10
false === !!0
这里有很多很棒的答案,但如果你读到这里,这帮助我“找到答案”。在Chrome(等)中打开控制台,然后开始键入:
!(!(1))
!(!(0))
!(!('truthy'))
!(!(null))
!(!(''))
!(!(undefined))
!(!(new Object())
!(!({}))
woo = 'hoo'
!(!(woo))
...etc., etc., until the light goes on ;)
当然,这些都和仅仅打字一样!!但添加的括号可能有助于使其更易于理解。
a = 1;
alert(!a) // -> false : a is not not defined
alert(!!a) // -> true : a is not not defined
对于a、 它检查a是否未定义,而!!a检查变量是否已定义。
!!a与相同!(!a)。如果定义了a,则a为真!a是假的,而且!!a为真。