了解嵌套三元运算符的简单方法? [英] Easy way to understand nested ternary operators?

查看:94
本文介绍了了解嵌套三元运算符的简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的启发式方法来理解如何读取嵌套三元运算符?
我在某人的源代码中遇到了这个问题,无法理解。一个简单的三进制很容易:

Is there a simple heuristic for understanding how to read nested ternary operators? I came across this in someone's source code and can't grok it. A simple ternary is easy:

isRed = color == 'red' ? true : false

但是您如何阅读以下内容?我可以将第一个与最后一个对齐,然后将第二个与最后一个对齐吗?还是我必须将其解析为if / else树?

But how do you read the following? Can I just line up the first with the last and the second with the second to last, or must I parse this into an if/else tree in my head?

var offset =
  ( hasFrozenRows )
    ? ( options.frozenBottom )
    ? ( row >= actualFrozenRow )
    ? ( h < viewportTopH )
    ? ( actualFrozenRow * options.rowHeight )
    : h
    : 0
    : ( row >= actualFrozenRow )
    ? frozenRowsHeight
    : 0
    : 0;

重新标记,看起来像这样,这几乎可以理解(?)

Retabbed, it can look like this, which is almost understandable (?)

      var offset =
        ( hasFrozenRows ) ?
          ( options frozenBottom ) ?
            ( row >= actualFrozenRow ) ?
              ( h < viewportTopH ) ?
                ( actualFrozenRow * options.rowHeight )
                :
                h
              :
              0
            :
            ( row >= actualFrozenRow ) ?
              frozenRowsHeight
              :
              0
            :
            0;


推荐答案

我认为,如果您尝试将其读为一系列的检查此如果为true,则此其他

I think you could have more luck if you try to read it as a series of check this, if true then this, else that.

为此,放置可能更容易:运算符放在行首,并像在流程图上的箭头一样标记为是和否的箭头来读取它们。例如:

For this, it might be easier to put the ? and : operators at the beginning of lines, and read them as if they were arrows on a flowchart, labeled "yes" and "no". e.g.:

cond1 
  ? cond2 
    ? cond3 
      ? res1 
      : res2
    : res3
  : res4

读为:

cond1?
  yes -> is cond2 
    yes -> is cond3?
      yes -> res1 
      no -> res2
    no -> res3
  no -> res4

这仍然不易理解,我同意所有这样的评论代码的确应该重写为可读的。

That still doesn't make this very readable, and I agree with all the comments saying this kind of code should really be rewritten to be readable.

这篇关于了解嵌套三元运算符的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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