最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Typescript ternary operator short form - Stack Overflow

programmeradmin1浏览0评论

I am inside a for loop trying to add up a number. The code is working fine, but I was asking myself if there might be shorter form for the following line:

price = ve.select ? price + ve.price : price;

if ve.select is true, the price is increased by ve.price, if its false, then price stays. I am searching for something similar like this line (I know this code snippet does not work):

price = ve.select ? price + ve.price;

I am inside a for loop trying to add up a number. The code is working fine, but I was asking myself if there might be shorter form for the following line:

price = ve.select ? price + ve.price : price;

if ve.select is true, the price is increased by ve.price, if its false, then price stays. I am searching for something similar like this line (I know this code snippet does not work):

price = ve.select ? price + ve.price;
Share Improve this question asked Sep 14, 2020 at 11:41 Niklas MeierNiklas Meier 471 gold badge2 silver badges8 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

You have several options:

  1. An if statement

    if (ve.select) {
        price += ve.price;
    }
    

    Or if you prefer it on one line:

    if (ve.select) price += ve.price;
    
  2. The conditional operator version you've shown:

    price = ve.select ? price + ve.price : price;
    

    ...but note that it does an unnecessary assignment when ve.select is falsy (though as price is presumably a simple variable that's not an issue; with an object property that might be an accessor property it can matter).

  3. Using the && (logical AND) operator:

    ve.select && price += ve.price;
    

    But note that this is really just an if statement in disguise.

  4. Tamás Sallai's answer providing an alternative use of the conditional operator (price += ve.select ? ve.price : 0;).

I'd reverse the ternary and use +=:

price += ve.select ? ve.price : 0;
发布评论

评论列表(0)

  1. 暂无评论