我看到一些代码似乎使用了我不认识的运算符,以两个感叹号的形式,像这样:!!。有人能告诉我这个接线员做什么吗?
我看到这件事的背景是,
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
我看到一些代码似乎使用了我不认识的运算符,以两个感叹号的形式,像这样:!!。有人能告诉我这个接线员做什么吗?
我看到这件事的背景是,
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
当前回答
这里有很多很棒的答案,但如果你读到这里,这帮助我“找到答案”。在Chrome(等)中打开控制台,然后开始键入:
!(!(1))
!(!(0))
!(!('truthy'))
!(!(null))
!(!(''))
!(!(undefined))
!(!(new Object())
!(!({}))
woo = 'hoo'
!(!(woo))
...etc., etc., until the light goes on ;)
当然,这些都和仅仅打字一样!!但添加的括号可能有助于使其更易于理解。
其他回答
这只是逻辑NOT运算符,两次。它用于将某些内容转换为布尔值,例如:
true === !!10
false === !!0
它是双重布尔否定。它通常用于检查值是否未定义。
以下是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将是真的,还有一个!这将是错误的。
const foo=“bar”;console.log(!!foo);//布尔值:真
! 对值求反(反转),并始终返回/生成布尔值。所以!”bar'将产生false(因为'bar'是truthy=>否定+布尔值=false)。附加的!运算符,该值再次被求反,因此false变为true。
它将所有的东西都强制为布尔值。
例如:
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