我尝试使用三元运算符,而不是使用 if else 语句,但语句中某处存在语法错误。
有人能告诉我哪里出错了吗?
声明是:
my_alert(status ? ('Accepted', 'alert-success') : ('Declined', 'alert-info'))
- my_alert 是一个有 2 个参数的函数。
- 状态仅评估为 true 或 false。
- 当我向上面的表达式传递超过 1 个参数时,它不喜欢使用逗号。
在 Chrome 和 Firefox 中,当该函数运行时,它会显示“alert-success”或“alert-info”。它错过了第一个参数。
我在 stackoverflow 上寻找答案,但它无论如何都告诉我我正在做的事情是正确的。
任何帮助都会很棒。
最佳答案
嗯,comma operator执行以下操作:
The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.
这意味着,('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);
关于javascript - javascript 三元运算符中逗号的正确使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14758672/