Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 most codebases I've ever seen or worked with, the comma operator is never used this way as it's far more confusing than it is helpful.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...