最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - single return of ternary operator - Stack Overflow

programmeradmin1浏览0评论

I wonder if possible to write ternary operator for single return. I tried google online, but couldn't find an answer. or it doesnot called ternary operator??

Thank you very much for your advice.

If(A == 1) execute_function(); into A == 1 ? execute_function() //???Possible???

I wonder if possible to write ternary operator for single return. I tried google online, but couldn't find an answer. or it doesnot called ternary operator??

Thank you very much for your advice.

If(A == 1) execute_function(); into A == 1 ? execute_function() //???Possible???

Share Improve this question asked Jan 11, 2013 at 9:40 MicahMicah 4,5508 gold badges32 silver badges40 bronze badges 8
  • 1 Why? The ternary just isn't appropriate here in my opinion. – Lloyd Commented Jan 11, 2013 at 9:42
  • Sorry, i am a noob, so we dont use ternary operator in this way? – Micah Commented Jan 11, 2013 at 9:42
  • 1 why not just execute_function(exists); ? – Tony Hopkinson Commented Jan 11, 2013 at 9:43
  • 1 Same logic though, execute_function(A == 1); – Lloyd Commented Jan 11, 2013 at 9:45
  • 1 @Till You can consider ternary operation as an alternative to if-then-else. So, instead of writing if(condition) doSomething else doSomethingElse you can write condition ? doSomething : doSomethingElse In your case you have just the if condition, while the else is empty, so as @Lloyd wrote ternary is not appropriate in your case – ThanksForAllTheFish Commented Jan 11, 2013 at 9:47
 |  Show 3 more comments

4 Answers 4

Reset to default 24

Here is the shortest way.

A == 1 && execute_function();

yes:

(exists == 1) ? execute_function() : false;

runs function if exists is true else wont

Added: Doing just like following would be better:

if( A == 1 ) {
  execute_function();
}

As using ternary operator in above case is not so fruitful, as you are checking only for the true side of the condition and do not care about what's in the false side.

condition ? (runTrue) : (runFalse);

is available in javascript.

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator

As someone already mentioned, A == 1 && execute_function(); is the shortest. However, another option is to use a single line if statement:

if( A == 1 ) execute_function();

发布评论

评论列表(0)

  1. 暂无评论