“if”是双&符号的简写

问题描述 投票:1回答:3

我看过这些行代码。

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

这是一个简写

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

谢谢 ;)

javascript if-statement shorthand
3个回答
1
投票

是的,这两个在执行中是等价的。

function test(value) {
  console.log(value);
  
  value && console.log("\texecyted 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()

这只是略微夸张,但完全有可能在类似的情况下结束。如果您的代码与单个条件和单个操作一样简单,那么使用内联条件和if语句可以节省2个字节

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

0
投票

不完全是。

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

如果this.tween在这个陈述中是真正的价值,它将被评估并保持在那里。所以它就像这段代码。

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

0
投票

是的,这是上述代码的简短手牌。如果this.tween未定义,则不会执行“&&”之后的代码。之后,将执行“,”之后的代码。这里有些例子:

this.a= undefined;
this.b= 20;
this.a && this.b.toString(),   // if a is true then b will be executed and converted to string
  console.log(this.b); // if a is true the output will be a string but in this case, a is undefined and the string conversion didn't happen, the console returns an integer

this.a = 10;
this.b=20
this.a && this.b.toString(),
  console.log(this.b); // this will return a string
  
if(this.a){ // if a is true be will be converted to string
this.b = parseInt(this.b);
}
this.a = this.b;  
console.log(this.a) // if a is true be will be converted back to integet and assigend to a

如果a未定义

// a is undefined then
this.a = undefined;
this.b=20
this.a && this.b.toString(),
  console.log(this.b); // this will return a integer
  
if(this.a){ // since a is undefined it will fail and conversion won't take place
this.b.toString();
}
this.a = this.b;  
console.log(this.a) // a integer is returned 
© www.soinside.com 2019 - 2024. All rights reserved.