javascript 是 !!在 if 语句中检查真值的最佳实践
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26906294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is !! a best practice to check a truthy value in an if statement
提问by Bargitta
In angular.js, there are some code snippets use !!
to check whether a value is truthy in if condition.
在 angular.js 中,有一些代码片段用于!!
检查 if 条件下的值是否为真。
Is it a best practice? I fully understand in return value or other assignment !! is used to make sure the type is Boolean. But is it also true for condition checks?
这是最佳做法吗?我完全理解返回值或其他赋值!!用于确保类型为布尔值。但条件检查也是如此吗?
if (!!value) {
element[name] = true;
element.setAttribute(name, lowercasedName);
} else {
element[name] = false;
element.removeAttribute(lowercasedName);
}
回答by Denys Séguret
No, !!
is totally useless in a if
condition and only confuses the reader.
不,!!
在某种if
情况下完全没有用,只会让读者感到困惑。
Values which are translated to true
in !!value
also pass the if
test because they're the values that are evaluated to true
in a Boolean context, they're called "truthy".
转换为true
in 的值!!value
也通过if
测试,因为它们是true
在布尔上下文中计算的值,它们被称为"truthy"。
So just use
所以只需使用
if (value) {
回答by Timothy Shields
!!value
is commonly used as a way to coerce value
to be either true
or false
, depending on whether it is truthy or falsey, respectively.
!!value
通常用作强制value
为true
或 的一种方式false
,分别取决于它是真还是假。
In a control flow statement such as if (value) { ... }
or while (value) { ... }
, prefixing value
with !!
has no effect, because the control flow statement is already, by definition, coercing the value
to be either true
or false
. The same goes for the condition in a ternary operator expression value ? a : b
.
在诸如if (value) { ... }
or 之类的控制流语句中while (value) { ... }
,前缀value
with!!
无效,因为根据定义,控制流语句已经将 强制value
为true
or 或false
。三元运算符表达式中的条件也是如此value ? a : b
。
Using !!value
to coerce value
to true
or false
is idiomatic, but should of course only be done when it isn't made redundant by the accompanying language construct.
使用!!value
to coerce value
totrue
或false
是惯用的,但当然应该只在它没有被附带的语言结构变得多余时才使用。