How to I execute multiple functions on the result

2019-05-23 05:36发布

问题:

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();

Is this possible?

回答1:

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

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 as it's more confusing than helpful most of the time.

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



回答2:

You can always wrap anything into an anonymous function and call it immediately, the so called Immediately Invoked Function Expression (IIFE), like so

isTrue ? (function() { functionOne(); functionTwo() })() : functionThree();

But as you can see it looks pretty darn terrible and is a pretty bad misuse of the ternary operator (it doesn't return anything useful) so I'd really recommend against doing that.