[英]Javascript complex One-liner if statements
First time saw such ternary expressions: 第一次看到这样的三元表达式:
var somevar = b1 ? b2 ? b3 : b4 : b5 ? b6 : b7 ? b8 : b9 ? b10 : b11
Having a hard time understanding and converting it to: 很难理解并将其转换为:
if (b1) {
} else if (bx) {
}
I've looked everywhere and can't seem to find the answer to this. 我到处寻找,似乎无法找到答案。
Just add parentheses. 只需添加括号。
var somevar = (b1 ? (b2 ? b3 : b4) : (b5 ? b6 : (b7 ? b8 : (b9 ? b10 : b11))))
Ie 即
if (b1) {
if (b2) {
b3
} else {
b4
}
} else {
if (b5) {
b6
} else {
if (b7) {
b8
} else {
if (b9) {
b10
} else {
b11
}
}
}
}
Or to make it shorter. 或者缩短它。
if (b1) {
if (b2) {
b3
} else {
b4
}
} else if (b5) {
b6
} else if (b7) {
b8
} else if (b9) {
b10
} else {
b11
}
Start from the far right. 从最右边开始。 whenever you find
a ? b : c
每当你找到
a ? b : c
a ? b : c
add parentheses around it. a ? b : c
在它周围添加括号。
For example: 例如:
a ? b ? c : d : e
a ? (b ? c : d) : e
(a ? (b ? c : d) : e)
Firstly convert it into parenthesis:
(b1 ?
(b2 ? b3 : b4 ) : (b5 ?
b6 : (b7 ?
b8 : (b9 ? b10 : b11)
)
)
)
Then according to it use following code: 然后根据它使用以下代码:
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
}
}
}
Clearly I would suggest torturing the person who wrote such code, but in lieu of that you could write this: 很明显,我建议折磨编写此类代码的人,但代之以你可以这样写:
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;
}
}
}
}
Here is my solution: 这是我的解决方案:
if (b1) {
if (b2) {
b3
} else {
b4
}
} else if (b5x) {
b6
} else if (b7) {
b8
} else if (b9) {
b10
} else {
b11
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.