我看到一些代码似乎使用了我不认识的运算符,以两个感叹号的形式,像这样:!!。有人能告诉我这个接线员做什么吗?
我看到这件事的背景是,
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
我看到一些代码似乎使用了我不认识的运算符,以两个感叹号的形式,像这样:!!。有人能告诉我这个接线员做什么吗?
我看到这件事的背景是,
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
当前回答
使用逻辑not运算符两次。
这意味着!true=false和!!true=真。
其他回答
我怀疑这是C++遗留下来的东西,在那里人们会重写!运算符,但不是布尔运算符。
因此,在这种情况下,要获得否定(或肯定)答案,首先需要使用!运算符来获取布尔值,但如果您想检查正数,则可以使用!!。
它将所有的东西都强制为布尔值。
例如:
console.log(undefined); // -> undefined
console.log(!undefined); // -> true
console.log(!!undefined); // -> false
console.log('abc'); // -> abc
console.log(!'abc'); // -> false
console.log(!!'abc'); // -> true
console.log(0 === false); // -> false
console.log(!0 === false); // -> false
console.log(!!0 === false); // -> true
看来是!!运算符导致双重否定。
var foo = "Hello, World!";
!foo // Result: false
!!foo // Result: true
简单地说!!只返回一个布尔值,如果对象不是null或undefined,则返回true,否则返回false。
你可以这么说!!object等于if(object)返回true,否则返回false。
就这么简单!
以下是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将是真的,还有一个!这将是错误的。