Javascript complex One-liner if语句

时间:2015-12-19 11:59:15

标签: javascript

第一次看到这样的三元表达式:

SELECT 
 CustomerIds.CustomerID
 ,(SELECT OrderDate FROM Table1
   WHERE Table1.CustomerID = CustomerIds.CustomerID
   ORDER BY OrderDate ASC
   LIMIT 1 OFFSET 2) AS OrderDate
FROM
 (SELECT CustomerID 
  FROM Table1
  GROUP BY CustomerID
  HAVING COUNT(*) >= 3) AS CustomerIds;

很难理解并将其转换为:

var somevar = b1 ? b2 ? b3 : b4 : b5 ? b6 : b7 ? b8 : b9 ? b10 : b11

我到处寻找,似乎无法找到答案。

3 个答案:

答案 0 :(得分:2)

Firstly convert it into parenthesis: 
(b1 ? 
     (b2 ? b3 :  b4 ) :   (b5 ? 
                               b6 : (b7 ? 
                                         b8 : (b9 ? b10 : b11) 
                                     )
                            )
  )

然后根据它使用以下代码:

  var somevars;
  if(b1)
  {
    if(b2) somevars=b3
    else somevars=b4
  }
  else 
  {
    if(b5) 
       somevars=b6
    else 
    {
      if(b7) 
      {
        somevars=b8
      }
      else  
      {
        if(b9) somevars=b10
        else somevars=b11
      }
    }
  }

答案 1 :(得分:1)

显然,我建议折磨编写此类代码的人,但代之以你可以这样写:

var somevar;

if (b1) {
    if (b2) {
        somevar = b3;
    } else {
        somevar = b4;
    }
} else {
    if (b5) {
        somevar = b6;
    } else {
        if (b7) {
            somevar = b8;
        } else {
            if (b9) {
                somevar = b10;
            } else {
                somevar = b11;
            }
        }
    }
}

答案 2 :(得分:0)

这是我的解决方案:

if (b1) {
    if (b2) {
        b3
    } else {
        b4
    }
} else if (b5x) {
    b6
} else if (b7) {
    b8
} else if (b9) {
    b10
} else {
    b11
}