如果变量定义了陷阱,则为true或false

Ale*_*lex -4 javascript

如果一个值必须定义为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工作....

Mik*_*uel 6

!操作者总是返回任一truefalse,所以假设的评价x完成通常,!!x是一个布尔值,它相当于Boolean(x)其中Boolean是EcmaScript的内置函数.

http://es5.github.com/#x11.4.9

11.4.9逻辑NOT运算符(!)

生产UnaryExpression:! UnaryExpression的计算方法如下:

  1. 设expr是评估UnaryExpression的结果.
  2. 设oldValue为ToBoolean(GetValue(expr)).
  3. 如果是oldValue true,则返回false.
  4. 返回true.

http://es5.github.com/#x9.2解释了ToBoolean的工作原理

9.2 ToBoolean

抽象操作ToBoolean根据表11将其参数转换为Boolean类型的值:

表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
Run Code Online (Sandbox Code Playgroud)

上表解释了大部分示例,但可能并不明显

 console.log(boolCheck());
Run Code Online (Sandbox Code Playgroud)

false.当你调用比形式参数的实际参数较少的功能,额外的参数的值undefined,正如上面显示的表!!undefinedfalse.


做的有什么问题:!!someValue

意图不太明确Boolean(someValue),但它将在各个平台上保持一致,大多数有经验的Javascript开发人员都会识别它.