!运算符总是返回trueor ,因此false假设评估x正常完成,!!x是一个布尔值,相当于EcmaScript 内置函数Boolean(x)where is。Boolean
http://es5.github.com/#x11.4.9说
11.4.9 逻辑非运算符 ( !)
产生式 UnaryExpression : ! UnaryExpression的评估如下:
- 令 expr 为计算 UnaryExpression 的结果。
- 让 oldValue 为 ToBoolean(GetValue(expr))。
- 如果 oldValue 是
true,则返回false。
- 返回
true。
http://es5.github.com/#x9.2解释了ToBoolean 的工作原理
9.2 ToBoolean
根据表 11,抽象操作 ToBoolean 将其参数转换为布尔类型的值:
表 11 - ToBoolean 转换
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
上表解释了您的大部分示例,但原因可能并不明显
console.log(boolCheck());
是false。当你调用一个实际参数比形式参数少的函数时,额外的参数有值undefined,如上表!!undefined所示false。
这样做有什么问题吗:!!someValue?
其意图不如 清晰Boolean(someValue),但它可以跨平台始终如一地工作,并且大多数有经验的 Javascript 开发人员都会认出它。