三重感叹号的使用 [英] The use of the triple exclamation mark
问题描述
通过查看我们的一个项目的源代码,我发现在条件语句中使用三个感叹号的地方很多,例如:
Looking through the source code of one of our projects, I've found some amount of places where we're using three exclamation marks in conditional statements, like so:
if (!!!someVar) {
// ...
}
现在,我知道这不是一种很少使用的运算符,它只是连续三个否定,例如!(!(!someVar)))
.我不知道它的用途-我认为可以安全地将其替换为单个感叹号.以下是我尝试查找!!!a
不等于!a
的情况的尝试(直接从Google chrome控制台获取):
Now, I understand that this isn't some kind of rarely used operator, it's just three negations in a row, like !(!(!someVar)))
. I don't understand what's the use of it - in my opinion it can safely be replaced with single exclamation mark. Following are my attempts to find a case when !!!a
isn't equal to !a
(taken straight from the google chrome console):
var a = ''
""
!!!a === !a
true
a = 'string'
"string"
!!!a === !a
true
a = null
null
!!!a === !a
true
a = 12
12
!!!a === !a
true
a = {b: 1}
Object {b: 1}
!!!a.c === !a.c // a.c is undefined here
true
a = []
[]
!!!a === !a
true
a = [1,2]
[1, 2]
!!!a === !a
true
我错过了一些罕见(或显而易见)的案件吗?
Am I missing some rare (or obvious) case?
推荐答案
!a
和!!!a
之间没有区别,因为!!!a
只是!!(!a)
并且因为!a
是布尔值,所以
There is no difference between !a
and !!!a
, since !!!a
is just !!(!a)
and because !a
is a boolean, !!(!a)
is just its double negation, therefore the same.
这篇关于三重感叹号的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!