如何对三元运算的结果执行多个功能? [英] How to I execute multiple functions on the result of a ternary operation?

查看:388
本文介绍了如何对三元运算的结果执行多个功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个if / else语句,如果结果为true,则会导致调用两个函数。

I have an if/else statement that results in two functions being called if it evaluates as true.

if (isTrue) {
    functionOne();
    functionTwo();
} 
else {
    functionThree();
}

我希望能够将其放在这样的三元语句中:

I would like to be able to put that in a ternary statement like this:

isTrue ? (functionOne(), functionTwo()) : functionThree();

这可能吗?

推荐答案

您的示例确实是有效的javascript。 您可以使用逗号分隔表达式

Your example is indeed valid javascript. You can use a comma to separate expressions, and wrap that in a single statement with parentheses for the ternary.

var functionOne   = function() { console.log(1); }
var functionTwo   = function() { console.log(2); }
var functionThree = function() { console.log(3); }
var isTrue = true;

isTrue ? (functionOne(), functionTwo()) : functionThree();
// 1
// 2

isTrue = false;
isTrue ? (functionOne(), functionTwo()) : functionThree();
// 3

但是,这是不可取的。带有 if 语句的版本更加清晰易读,并且执行速度也一样快。在实践中,很少使用逗号运算符,因为它在大多数时候比有用的东西更令人困惑。

However, this is not advisable. Your version with an if statement is far more clear and readable, and will execute just as fast. In practice, the comma operator is rarely used as it's more confusing than helpful most of the time.

只是因为您可以,但这并不意味着您应该这样做。

Just because you can, doesn't mean you should.

这篇关于如何对三元运算的结果执行多个功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆