JavaScript:“!!”是什么意思?

时间:2014-07-30 21:25:33

标签: javascript

我刚刚遇到这个

var strict = !! argStrict;

我无法帮助但是想知道!!的含义是什么?这是双重否定吗?看起来非常多余,php.js中的人不太可能在这种情况下使用它?

来源:http://phpjs.org/functions/in_array/

4 个答案:

答案 0 :(得分:4)

它强制类型成为一个真正的布尔值而不是" truthy"值。 例子:

var a = (1 === true) // comes out as false because 1 and true are different types and not exactly the same

var b = ((!!1) === true) // comes out as true because the 1 is first converted to a boolean value by means of negation (becomes false) and then negated a second time (becomes true)

答案 1 :(得分:1)

这基本上意味着"转换为布尔值"。

它否定了它两次,所以argStrict是" falsy",然后!argStrict是真的,!!argStrictfalse

答案 2 :(得分:1)

返回boolean值。 falseundefinednull0''任意truetruthy

答案 3 :(得分:1)

这是slacker parsing的一个例子。

如果你有一个变量,例如一个字符串,并且你想将它转换成一个布尔值,你可以这样做:

if (myString) {
    result = true;
}

这就是说,如果myString未定义,null,空,数字0,布尔值为false,则将我的字符串设置为布尔值为true ...

但它更快,更酷,可以让它翻倍:

result = !! myString;

其他例子包括....

//Convert to number
result = +myString;

//Bang Bang Wiggle - coerces an indexOf check into a boolean
result !!~myString.indexOf('e');
相关问题