首页 > 解决方案 > 带有双 & 符号的 "if" 简写

问题描述

我看过这些行代码。

this.tween && this.tween.kill(),
this.tween = TweenMax.to(object, 1, {
  ...
})

这是简写​​吗

if(this.tween){
  this.tween.kill();
}
this.tween = TweenMax.to(object, 1, {
  ...
})

谢谢 ;)

标签: javascriptif-statementampersandshorthanddouble-ampersand

解决方案


是的,两者在执行上是等价的。

function test(value) {
  console.log(value);
  
  value && console.log("\texecute using AND");
  if (value) console.log("\texecuted using if");
}

test(true);
test(false);
test("string");
test(""); //empty string
test(0);
test(null);
test(undefined);
test(1);
test({});

然而,话虽如此,这并不是 JavaScript 的惯用用法。所以你可能不应该使用这个结构,因为它可能会让其他开发人员失望。您的示例很好地说明了这一点,代码看起来像

function f (condition) {
  condition && one(),
  two();
}

function one() {
  console.log("one");
}

function two() {
  console.log("two")
}

f(false);
f(true);

这确实有效

function f(condition) {
  if (condition) {
    one();
 }

  two();
}

所以,one()会被执行几次,而two总是会被执行。然而,在不知道优先规则的情况下,它可能看起来像两者 one(),并且two()会被有条件地执行。这是一个容易犯的错误,如果它是一个复杂的条件和逻辑,那就更容易了

person.account.moneyAmount > 0 && creditor.getDebt(person).moneyOwed > 0 && person.account.moneyAmount > creditor.getDebt(person).moneyOwed  && (deductTaxes(payAndReturnAmount(person, creditor)), printStatement()), printHello()

这只是稍微夸大了一点,但完全有可能最终陷入类似的境地。如果您的代码与单个条件和单个操作一样简单,那么您可以从使用内联条件与语句中节省 2个字节if

condition && action()
if (condition) action()
                     ^^
"extra" characters __||

推荐阅读