一个有点痛苦的三重嵌套三元运算符 [英] A somewhat painful triple-nested ternary operator

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

问题描述

我查看 Raphael.js 的源代码,了解他如何将RGB值转换为HSB。我发现了他所做的功能,当我碰到这个漂亮的三嵌套三元运算符时,我正在将它转换为Python:

I went looking through Raphael.js's source code to find out how he converted RGB values to HSB. I found out the function he did it in and I was in the process of converting it to Python when I bumped into this nice triple-nested ternary operator:

H = (C == 0 ? null :
    V == r ? (g - b) / C :
    V == g ? (b - r) / C + 2 :
             (r - g) / C + 4
    );

它让我循环,因为Python没有与Javascript相同的三元运算符。我花了一段时间查看它并最终将这个有点理智的代码(仅使用if / else)从中删除:

It threw me for a loop because Python doesn't have the same kind of ternary operator that Javascript does. I spent a while looking over it and eventually hashed this somewhat saner code (using only if/else) out of it:

if (C == 0) {
    H = null;
} else {
    if(V == r) {
        H = (g - b) / C;
    } else {
        if(V == g) {
            H = (b - r) / C + 2;
        } else {
            H = (r - g) / C + 4;
        }
    }
}

我的解释是否正确?我只是问这个,因为如果它不正确,我面临着一个很多的调试。所以。我得到了吗?

Was my interpretation correct? I'm only asking this because if it isn't correct, I'm faced with a lot of debugging. So. Did I "get it"?

推荐答案

我认为你可以这样做以避免深度嵌套:

I think you can have this to avoid the deep nesting:

var H

if(C == 0){
    H = null;
}
else if(V == r){
    H = (g - b) / C;
}
else if (V == g){
    H = (b - r) / C + 2;
}
else {
    H = (r - g) / C + 4;
}

这篇关于一个有点痛苦的三重嵌套三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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