2025-03-02 06:00:05

两个感叹号?

可能的重复: 这是什么!!(不是不是)操作符在JavaScript? 这是什么!!操作符(双感叹号)在JavaScript中是什么意思?

我在调试一些代码时看到了这个:

var foo.bar = 0; // this is actually passed from another function, adding it for context

function(foo) {
    var someVar = !!foo.bar;

    if (foo.bar) {
      // ..stuff happens
    } else {
      // .. something else happens
    }
}

好吧,我的问题是这有什么意义!!?所有这些都是使0 === false。

与布尔(foo.bar)相比,使用它有什么好处吗? foo。Bar可以在if as中进行评估,因为0 === false已经存在,那么为什么要进行转换呢?(someVar在其他任何地方都不会被重用)


当前回答

如上所述,它强制使用布尔类型的对象。你可以自己看看:

(函数类型检查(){ Var a = "a"; Var b = ! Var c = !!a; Console.log ("var a =", a, typeof(a)) Console.log ("var b =", b, typeof(b)) Console.log ("var c =", c, typeof(c)) }) ();

如果您只是进行比较,那么转换只是为您节省了稍后的类型强制转换。

供您参考,以下值在JavaScript中被强制为FALSE:

假 0 "" 零 未定义的

其他回答

我认为答案是没有什么意义。我们可以推测它是如何产生的:

maybe an earlier version of the function used someVar in multiple places, or in ways that genuinely benefited from having true or false, so this made more sense. maybe the person who wrote the function is so used to using !! to convert to true/false that (s)he didn't even notice that it wasn't necessary here. maybe the person who wrote the function feels that every computation (in this case, Boolean conversion) should be given a meaningful name by assigning some variable to its result. maybe, since Boolean conversion in JavaScript is surprisingly error-prone (in that e.g. new Boolean(false) is a true-valued value), the person who wrote the function feels that it should always be done explicitly rather than implicitly — even though the effect is the same — just to call attention to it as a potential point of error. this, of course, presupposes that the person who wrote the function thinks of !! as an "explicit" Boolean conversion. Technically it's not — it uses the same implicit Boolean conversion that if does — but if you're used to this idiom, then it amounts to an explicit conversion.

但在我的主观意见,这些理由都不是很好!

如上所述,它强制使用布尔类型的对象。你可以自己看看:

(函数类型检查(){ Var a = "a"; Var b = ! Var c = !!a; Console.log ("var a =", a, typeof(a)) Console.log ("var b =", b, typeof(b)) Console.log ("var c =", c, typeof(c)) }) ();

如果您只是进行比较,那么转换只是为您节省了稍后的类型强制转换。

供您参考,以下值在JavaScript中被强制为FALSE:

假 0 "" 零 未定义的

这将值转换为布尔值并确保为布尔类型。

"foo"      // Evaluates to "foo".
!"foo"     // Evaluates to false.
!!"foo"    // Evaluates to true.

如果foo。Bar被传递,那么它可能不是0,而是其他一些虚假的值。请看下面的真值表:

javascript真值表

''        ==   '0'           // false
0         ==   ''            // true
0         ==   '0'           // true
false     ==   'false'       // false
false     ==   '0'           // true
false     ==   undefined     // false
false     ==   null          // false
null      ==   undefined     // true
" \t\r\n" ==   0             // true

资料来源:Doug Crockford

当涉及到NaN值时,Javascript也变得非常奇怪。这是我唯一能想到的情况!!对===会有不同的行为。

NaN   ===  NaN     //false
!!NaN === !!NaN    //true

// !!NaN is false