jer*_*ome 5 javascript variables
我可以澄清一下我为什么要使用它吗?
myVar = !!someOtherVar;
Run Code Online (Sandbox Code Playgroud)
在非严格类型的语言中,!运算符将值转换为布尔值.两次这样做相当于说
myVar = (boolean)someOtherVar
Run Code Online (Sandbox Code Playgroud)
请注意,建议不要将其用于代码清晰度.
(重写以澄清,简化)
该语句执行几个不同的操作:
myVar = // This portion is a regular assignment, it will store the value of the suffix
!!someOtherVar; // This portion is evaluated to a boolean result
Run Code Online (Sandbox Code Playgroud)
的!!someOtherVar,我想,是什么你真的问.答案很简单:它执行两个逻辑NOT操作来对抗真实性(Javascript'ism)someOtherVar.
换句话说,如果你理解了!运算符,那么它只结合了两个!!运算符(不是一个不同的运算符).通过这样做,它基本上返回布尔值的评估someOtherVar- 换句话说,它是来自任何类型的强制someOtherVar转换boolean.
所以...要完成这个,并注意以下结果myVar:
myVar = someOtherVar; // myVar will be whatever type someOtherVar is
myVar = !someOtherVar; // myVar will *always be boolean, but the inverse of someOtherVar's truthiness
myVar = !!someOtherVar; // myVar will *always be boolean, and be the equivalent of someOtherVar's truthiness
Run Code Online (Sandbox Code Playgroud)
这是一个双重否定,但它也适用于类型铸造.!somevar将返回一个布尔值(如果somevar是"truthy",则为true;如果是"falsey",则为false,根据Crockford的讲座).所以,!!somevar将是not(bool),因此它将是布尔.
| 归档时间: |
|
| 查看次数: |
322 次 |
| 最近记录: |