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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:39:50  来源:igfitidea点击:

Is !! a best practice to check a truthy value in an if statement

javascriptangularjstruthiness

提问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 ifcondition and only confuses the reader.

不,!!在某种if情况下完全没有用,只会让读者感到困惑。

Values which are translated to truein !!valuealso pass the iftest because they're the values that are evaluated to truein a Boolean context, they're called "truthy".

转换为truein 的值!!value也通过if测试,因为它们是true在布尔上下文中计算的值,它们被称为"truthy"

So just use

所以只需使用

if (value) {

回答by Timothy Shields

!!valueis commonly used as a way to coerce valueto be either trueor false, depending on whether it is truthy or falsey, respectively.

!!value通常用作强制valuetrue或 的一种方式false,分别取决于它是真还是假。

In a control flow statement such as if (value) { ... }or while (value) { ... }, prefixing valuewith !!has no effect, because the control flow statement is already, by definition, coercing the valueto be either trueor false. The same goes for the condition in a ternary operator expression value ? a : b.

在诸如if (value) { ... }or 之类的控制流语句中while (value) { ... },前缀valuewith!!无效,因为根据定义,控制流语句已经将 强制valuetrueor 或false。三元运算符表达式中的条件也是如此value ? a : b

Using !!valueto coerce valueto trueor falseis idiomatic, but should of course only be done when it isn't made redundant by the accompanying language construct.

使用!!valueto coerce valuetotruefalse是惯用的,但当然应该只在它没有被附带的语言结构变得多余时才使用。