三重叹号的使用

通过查看我们一个项目的源代码,我发现有些地方我们在条件语句中使用了三个感叹号,比如:

if (!!!someVar) {
// ...
}

现在,我明白这不是某种很少使用的运算符,它只是连续的三个否定,就像 !(!(!someVar)))。我不明白它有什么用——在我看来,它可以安全地被单一叹号所取代。下面是我试图找到一个案例当 !!!a不等于 !a(采取直接从谷歌铬控制台) :

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

我是不是漏掉了一些罕见的(或显而易见的)案例?

43068 次浏览

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 is the same as one exclamation mark. The key idea behind it is to improve visibility for the programmer. Compiler will optimize it as single '!' anyway.

Consider:

var x;
console.log(x == false);
console.log(!x, !x == true);
console.log(!!x, !!x == true, !!x == false);

... the console output is:

false
true true
false false true

notice how, even though x is "falsey" in the first use, it is not the same as false.

But the second use (!x) has an actual boolean - but it's the opposite value.

So the third use (!!x) turns the "falsey" value into a true boolean.

...with that in mind, the third exclamation point makes a TRUE negation of the original value (a negation of the "true boolean" value).

ETA:

OMG! I can't believe I didn't notice that this is a TRIPLE exclamation point question! Even after it was specifically pointed out to me.

So, while my answer is hopefully useful to someone, I have to agree with the others who have posted that a triple-exclamation is functionally the same as a single.

In JavaScript, it's a way to show that what you are evaluating is not a boolean but a truthy or falsy value.

So for truthy/falsy values you either use !! or !!!.

And for boolean values you either use ! or nothing.

This is simply for readability.