【问题标题】:Condense this javascript using ternary operators使用三元运算符压缩此 javascript
【发布时间】:2013-11-14 23:41:42
【问题描述】:

我希望将 rlPrice 分配给 0(如果未定义)或可用的已定义价格。下面这个就可以了。

if($('#rl option:selected').data("unit-price") == undefined){
    rlPrice = 0;
else{
    rlPrice = $('#rl option:selected').data("unit-price");
}

但是有没有办法用三元运算符做到这一点?

rlPrice = $('#rl option:selected').data("unit-price") OR 0;

【问题讨论】:

    标签: javascript ternary-operator ternary


    【解决方案1】:

    最快的方法是使用合并运算符:

    rlPrice = $('#rl option:selected').data("unit-price") || 0;
    

    看到这个link

    【讨论】:

    • +1 null coalescing 这是选择词。感谢您让我知道这一点,我喜欢这种干净的方法。
    • 请注意,|| js 运算符并不完全等于 c# 的 ??,请参阅链接页面上的说明
    • @user1671639 你的意思是apt word??
    【解决方案2】:

    三元运算符的形式为

    d = a ? b : c; 
    

    实际上,如果a 为真,则将b 分配给d,否则将c 分配给d。

    所以,替换上面语句中的真实表达式:

    rlPrice = $('#rl option:selected').data("unit-price") == undefined?0:$('#rl option:selected').data("unit-price")
    

    【讨论】:

      【解决方案3】:

      您的 if..else 语句使用 ?: 运算符进行精确化。

      rlPrice = $('#rl option:selected').data("unit-price") == undefined 
                 ? 0 
                 : $('#rl option:selected').data("unit-price");
      

      【讨论】:

        猜你喜欢
        • 2011-07-08
        • 2012-06-23
        • 2020-04-29
        • 2021-07-14
        • 2012-07-25
        • 2021-03-09
        • 2015-09-13
        • 2019-11-09
        • 2012-02-11
        相关资源
        最近更新 更多