我看到一些代码似乎使用了我不认识的运算符,以两个感叹号的形式,像这样:!!。有人能告诉我这个接线员做什么吗?
我看到这件事的背景是,
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
我看到一些代码似乎使用了我不认识的运算符,以两个感叹号的形式,像这样:!!。有人能告诉我这个接线员做什么吗?
我看到这件事的背景是,
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
当前回答
以下是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将是真的,还有一个!这将是错误的。
其他回答
这是检查未定义、“未定义”、null、“null”、“”
if (!!var1 && !!var2 && !!var3 && !!var4 ){
//... some code here
}
它将所有的东西都强制为布尔值。
例如:
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
!! 只是两次NOT运算符。净效果就是转换任何东西以确保布尔数据类型。例如
!!undefined为false!!0为假!!null为false!!anyobject为true!!真是真!!false是false!0为真!1为假!!'' 是假的
看来是!!运算符导致双重否定。
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将是真的,还有一个!这将是错误的。