如果一个值必须定义为true或false,基于检查另一个值,是否有任何问题:
!!someValue
Run Code Online (Sandbox Code Playgroud)
只需快速对抗chrome的引擎即可:
boolCheck=function(someValue){
return !! someValue;
}
console.log(boolCheck()); //false
console.log(boolCheck(undefined)); //false
console.log(boolCheck(null)); //false
console.log(boolCheck(1)); //true
console.log(boolCheck({va:1})); //true
console.log(boolCheck("someTS")); //true
console.log(boolCheck(boolCheck)); //true
Run Code Online (Sandbox Code Playgroud)
SEEMS工作....
的!操作者总是返回任一true或false,所以假设的评价x完成通常,!!x是一个布尔值,它相当于Boolean(x)其中Boolean是EcmaScript的内置函数.
http://es5.github.com/#x11.4.9说
11.4.9逻辑NOT运算符(
!)生产UnaryExpression:
!UnaryExpression的计算方法如下:
- 设expr是评估UnaryExpression的结果.
- 设oldValue为ToBoolean(GetValue(expr)).
- 如果是oldValue
true,则返回false.- 返回
true.
http://es5.github.com/#x9.2解释了ToBoolean的工作原理
9.2 ToBoolean
抽象操作ToBoolean根据表11将其参数转换为Boolean类型的值:
表11 - ToBoolean转换
Run Code Online (Sandbox Code Playgroud)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
上表解释了大部分示例,但可能并不明显
Run Code Online (Sandbox Code Playgroud)console.log(boolCheck());
是false.当你调用比形式参数的实际参数较少的功能,额外的参数的值undefined,正如上面显示的表!!undefined是false.
做的有什么问题:
!!someValue?
意图不太明确Boolean(someValue),但它将在各个平台上保持一致,大多数有经验的Javascript开发人员都会识别它.
| 归档时间: |
|
| 查看次数: |
119 次 |
| 最近记录: |