One liner that returns a value if evaluation is truthy and breaks if evaluation falsy?

问题: Here is a piece of code I have in several places in my code: req = this.getActiveRequestById(message.trans_id); if (!req) { break; } How can I rewrite this as a on...

问题:

Here is a piece of code I have in several places in my code:

req = this.getActiveRequestById(message.trans_id);
if (!req) {
    break;
}

How can I rewrite this as a one-liner?

EDIT I want to clarify that I need to store the return value in req for later use.


回答1:

Remove var assignment and apply the condition directly to the value:

if (!this.getActiveRequestById(message.trans_id)) break;

I would not suggest it but if you need to set a variable in a one liner if condition it should work:

 if (!(req = this.getActiveRequestById(message.trans_id))) break;

Notice that it generates confusion between comparison and assignment.


回答2:

if (!(reg = this.getActiveRequestById(message.trans_id))) break;
  • 发表于 2019-02-14 17:09
  • 阅读 ( 174 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除