Proper use of a comma in javascript ternary operator

给你一囗甜甜゛ 提交于 2019-12-24 01:44:08

问题


Rather than use an if else statement, I'm trying to use the ternary operator but have a syntax error somewhere in my statement.

Can someone tell me where I am going wrong?

Statement is:

my_alert(status ? ('Accepted', 'alert-success') : ('Declined', 'alert-info'))
  • my_alert is a function which has 2 parameters.
  • Status just evaluates to true or false.
  • When I pass more than 1 parameter into the above expression, it doesn't like the use of the comma.

In chrome and firefox when the function runs it displays 'alert-success' or 'alert-info'. It misses out the first parameter.

I've looked on stackoverflow for the answer but by all means it's telling me that what i'm doing is correct.

Any help would be great.


回答1:


Alternatively, you could just wrap the function call in the ternary statement...

status ? my_alert("Accepted", "alert-success") : my_alert("Declined", "alert-info");

UPDATE:

Robin van Baalen makes a good suggestion...

my_alert.apply(this, status ? ["Accepted", "alert-success"] : ["Declined", "alert-info"]);



回答2:


Well, the comma operator does the following:

The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.

That means, ('Accepted', 'alert-success') evaluates to 'alert-success' (as you already noticed). The comma here is different than the comma that separates function arguments. You cannot use it to pass two arguments to a function.

What you can do is store both arguments in an array and use .apply to pass them to the function:

// this is not the comma operator either, this is array literal syntax.
var args = status ? ['Accepted', 'alert-success'] : ['Declined', 'alert-info'];
my_alert.apply(null, args);



回答3:


I don't think ternary operators can be used to control two values like that:

How about separating them:

my_alert(($status?"Accepted":"Declined"),($status?"alert-success":"alert-info"));



回答4:


You can't use the comma like that. If you want to pass 2 parameters, you need to use 2 ternary statements.

my_alert((status ? 'Accepted' : 'Declined'), (status ? 'alert-success' : 'alert-info'));

In your case, the comma is read a the comma operator, which evaluates both operands and returns the last one. So, your ternary statement was equivalent to:

my_alert(status ? 'alert-success' : 'alert-info')


来源:https://stackoverflow.com/questions/14758672/proper-use-of-a-comma-in-javascript-ternary-operator

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