在JavaScript中,双感叹号(!!)技巧总是产生true或false吗

Does the double-exclamation (!!) trick always produce true or false in JavaScript?

本文关键字:true false JavaScript 感叹      更新时间:2023-09-26

请原谅我的提问(我来自C/C++世界)

我很好奇下一行在JavaScript中是否总是将bResult设置为truefalse

var bResult = !!someVariable;

用于将任何东西转换为布尔类型的速记,与相同

var bResult = Boolean(someVariable);

https://stackoverflow.com/a/264037/3094153

根据ECMAScript Language Specification

生产UnaryExpression:!UnaryExpression的计算结果为如下:

设oldValue为ToBoolean(GetValue(expr))。

var bResult = !!someVariable;的情况下,对第一个逻辑Not运算符进行评估

oldvalue = !(ToBoolean(value of someVariable))

有关如何将不同的数据类型转换为布尔值,请参见下表。因此,将根据"someVariable"的类型和值进行转换。

Argument Type   Result
Undefined       false
Null            false
Boolean         The result equals the input argument (no conversion).
Number          The result is false if the argument is +0, -0, or NaN; otherwise the result is true.
String          The result is false if the argument is the empty String (its length is zero); otherwise the result is true.
Object          true

如果oldValue为true,则返回false。返回true。

这完成了对第一个逻辑NOT运算符的评估

bResult = !(oldValue)//以相同的方式再次评估第二个逻辑NOT运算符,并获得结果。

因此,结果取决于数据类型和"somevariable"的值,这不是一个技巧。