在javascript三元运算符中正确使用逗号

时间:2013-02-07 18:48:43

标签: javascript ternary-operator comma-operator

我没有使用if else语句,而是尝试使用三元运算符,但在语句中的某处有语法错误。

有人能告诉我哪里出错了吗?

声明是:

my_alert(status ? ('Accepted', 'alert-success') : ('Declined', 'alert-info'))
  • my_alert是一个有2个参数的函数。
  • 状态只评估为真或假。
  • 当我将多个参数传递给上面的表达式时,它不喜欢使用逗号。

在chrome和firefox中,当函数运行时,它会显示“alert-success”或“alert-info”。它错过了第一个参数。

我查看了stackoverflow的答案,但无论如何它告诉我我正在做的是正确的。

任何帮助都会很棒。

4 个答案:

答案 0 :(得分:11)

嗯,comma operator执行以下操作:

  

逗号运算符计算它的两个操作数(从左到右)并返回第二个操作数的值。

这意味着,('Accepted', 'alert-success')评估为'alert-success'(正如您已经注意到的那样)。这里的逗号与分隔函数参数的逗号不同。您不能使用它将两个参数传递给函数。

您可以做的是将两个参数存储在一个数组中,并使用.apply将它们传递给函数:

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

答案 1 :(得分:5)

我认为三元运算符不能用于控制两个值:

如何分离它们:

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

答案 2 :(得分:2)

或者,您可以在三元语句中包装函数调用...

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

更新:

Robin van Baalen提出了一个很好的建议......

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

答案 3 :(得分:0)

您不能使用这样的逗号。如果要传递2个参数,则需要使用2个三元语句。

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

在您的情况下,逗号被读为comma operator,它评估两个操作数并返回最后一个操作数。所以,你的三元陈述相当于:

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