在javascript三元运算符中正确使用逗号 [英] Proper use of a comma in javascript ternary operator

查看:52
本文介绍了在javascript三元运算符中正确使用逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

有人可以告诉我我要去哪里了吗?

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?

声明为:

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

  • my_alert是一个具有2个参数的函数.
  • 状态仅计算为是或否.
  • 当我在上面的表达式中传递多个参数时,它不喜欢使用逗号.
  • 在chrome和firefox中,函数运行时会显示"alert-success"或"alert-info".它错过了第一个参数.

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

    我一直在寻找stackoverflow的答案,但总的说来,这告诉我我在做的事是正确的.

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

    任何帮助都会很棒.

    推荐答案

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

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

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

    更新:

    罗宾·范·巴伦(Robin van Baalen)提出了一个很好的建议...

    Robin van Baalen makes a good suggestion...

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

    这篇关于在javascript三元运算符中正确使用逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆