How to I execute multiple functions on the result of a ternary operation?

南笙酒味 提交于 2020-01-13 14:54:20

问题


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 used 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.



来源:https://stackoverflow.com/questions/28950027/how-to-i-execute-multiple-functions-on-the-result-of-a-ternary-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!