javascript - 带有双 & 符号的 "if" 简写
问题描述
我看过这些行代码。
this.tween && this.tween.kill(),
this.tween = TweenMax.to(object, 1, {
...
})
这是简写吗
if(this.tween){
this.tween.kill();
}
this.tween = TweenMax.to(object, 1, {
...
})
谢谢 ;)
解决方案
是的,两者在执行上是等价的。
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 __||
推荐阅读
- c - 我的程序不会停止执行 if 语句但条件不满足
- python - 在python中同时运行一个函数和一个线程
- javascript - NextJS 路由器编码查询字符
- django - Django ORM 按日期分组并获取总值
- node.js - Nuxt:如何从 express 中获取会话值
- python - 无法使用 Selenium 填写表单:AttributeError:“WebDriver”对象没有属性“get_element_by_xpath”
- stored-procedures - Java Web with Weblogic, DB Informix 存储过程数据——不可能的问题
- html - 如何在 express/node.js 中动态定义嵌套路由
- javascript - 比较javascript中2个日期是否相同
- jquery - Choices JS Re-Initialize 不适用于动态行添加