简体   繁体   English

如果/其他则更有效地编写此方法

[英]More efficient way to write this if/else

I wrote a little check for an input field that counts the length and makes sure it is the proper amount. 我为输入字段写了一点检查,该字段计算长度并确保它是正确的数量。 It gets complex because it needs to allow either 9 digits or 1 letter and 5 digits. 它变得复杂,因为它需要允许9位数字或1个字母和5位数字。 The way I have it now works but the code hurts my brain, I would like to see what a more elegant solution would look like for this, maybe using ternary and/or switch? 我现在拥有它的方式可以工作,但是代码却伤了我的大脑,我想看看这样做更优雅的解决方案是什么样的,也许使用三元和/或切换?

So a little part of the not so pretty that I have in place now : 我现在已经准备的不太漂亮的一小部分:

if (len !== 9) {
    if (len == 1) {
        y.hide();
        n.show();
        valInput.text("You need 8 more numbers");
    } else {
        if (len == 2) {
            y.hide();
            n.show();
            valInput.text("You need 7 more numbers");
        } else {
            if (len == 3) {
                y.hide();
                n.show();
                valInput.text("You need 6 more numbers");
            } else {
                if (len == 4) {
                    y.hide();
                    n.show();
                    valInput.text("You need 5 more numbers");
                } else {
                    if (len == 5) {
                        y.hide();
                        n.show();
                        valInput.text("You need 4 more numbers");
                    } else {
                        if (len == 6) {
                            y.hide();
                            n.show();
                            valInput.text("You need 3 more numbers");
                        } else {
                            if (len == 7) {
                                y.hide();
                                n.show();
                                valInput.text("You need 2 more numbers");
                            } else {
                                if (len == 8) {
                                    y.hide();
                                    n.show();
                                    valInput.text("You need 1 more number");
                                } else {
                                    if (len > 9) {
                                        y.hide();
                                        n.show();
                                        valInput.text("Order number must be 9 digits");
                                        // gt 9
                                    }
                                    // 8
                                }
                                // 7
                            }
                            // 6
                        }
                        // 5
                    }
                    // 4
                }
                // 3
            }
            // 2
        }
        // 1
    }
    // this is not equal to 9
}

UPDATE 更新

Thanks for all the answers! 感谢所有的答案! Lots of good stuff, I will accept my favorite after I play for a while. 很多好东西,玩了一段时间后,我会接受我的最爱。 To clarify what happens when the proper requirements are met then the submit button fades in but not until it is validated. 为了弄清楚当满足适当的要求时会发生什么,然后提交按钮会淡出,但直到它被验证后才会出现。 Not sure if it is relevant but will mention that the function also runs as "live type" so the message with the count is returned after each .keyup() 不确定是否相关,但是会提到该函数也以“实时类型”运行,因此带有计数的消息在每个.keyup()之后返回

If you don't want to use switch, you can do something like this: 如果您不想使用switch,可以执行以下操作:

if (len < 9) {
    y.hide();
    n.show();
    valInput.text("You need " + (9 - len) + " more number(s)");
}
else if (len > 9) {
    y.hide();
    n.show();
    valInput.text("Order number must be 9 digits");
}
else {
    // all good here...
}

And if you don't like the "number(s)" part, just check if len is not 1, and add that "s" to the "number" . 如果您不喜欢"number(s)"部分,只需检查len是否不是1,然后将"s"添加到"number"

As those look all the same why not use this: 看起来一样,为什么不使用它:

if (len !== 9) {
    var diff = 9 - len;
    var value = ( 0 < diff ? "You need " + diff + " more numbers" : "Order number must be 9 digits" );
    y.hide();
    n.show();
    valInput.text(value);
}

I think you should calculate the remaining characters through javascript, since that's the only difference in all the other if else branches, so you can do something like this and would be much more readable: 我认为您应该通过javascript计算其余字符,因为这是其他所有分支(如果else分支)的唯一区别,因此您可以执行以下操作,并且可读性更高:

if (len !== 9) {
    y.hide();
    n.show();
    if (len > 9) {
        valInput.text("Order number must be 9 digits");
    }
    else{
        var remaining = 9 - len;
        valInput.text("You need " + remaining + " more numbers");
    }
}

In your particular case it looks like the validation is simple enough for something like this: 在您的特定情况下 ,对于这样的事情,验证似乎很简单:

function validate(len) {
    var msg;
    if (len == 9)
        return true;
    y.hide(); /* no need to duplicate these calls in each condition */
    n.show();
    if (len < 9)
        msg = 'You need ' + (9-len) + ' more number' + (len == 1 ? '' : 's') + '.';
    else
        msg = 'You entered ' + (len-9) + ' number' + (len == 1 ? '' : 's') + ' too many.;
    valInput.text(msg);
    return false;

}

Comment: === should be saved for when needed, not just to be fancy! 评论: ===应该在需要时保存,而不仅仅是花哨! Unfortunately so many are taught to avoid double equals rather than actually understanding its useful and helpful extra features like type conversion. 不幸的是,许多人被教导避免双重等于,而不是真正理解其有用和有用的额外特性,例如类型转换。 In this situation there is no reason whatsoever to use triple equals. 在这种情况下,没有任何理由使用三重等于。

But in general , such as if your sequence of conditionals does something more significant than alert a sequence of messages varying only by a consecutive integer, then use switch ... 但是通常 ,例如,如果您的条件序列比警告仅连续两个整数的消息序列具有更重要的意义,请使用switch ...

switch (len) {
case 1:

/* handle this case */;
    y.hide();
    n.show();
    valInput.text("You need 8 more numbers");
    break;
/* make sure to end case 1 with a break; */

case 2:
    y.hide();
    n.show();
    valInput.text("You need 7 more numbers");
    break;
/* make sure to end every case with a break; */

...
}

You can simplify this to: 您可以将其简化为:

  if (len !== 9) {
      valInput.text("You need " +  (9 -len ) + " more numbers");
       y.hide();
      n.show();
   }

Why even use a switch or a huge if ? 为什么即使使用switch或一个巨大的if

if(len == 9){
    // do stuff.
}else{
    y.hide();
    n.show();
    if(9 > len)
         valInput.text("You need " + (len - 9) + " less numbers");
    else 
         valInput.text("You need " + (9 - len) + " more numbers");
    valInput.text("Order number must be 9 digits");
}

Just declare the range of the values you want then concatenate the string. 只需声明所需值的范围,然后concatenate字符串即可。

the shortest alternative: 最短的选择:

(y.hide(), n.show(), valInput.text(
     len < 9 &&  "You need " + (9-len) + " more digits"
  || len > 9 && "too many ("+ (len-9) + ") digits" 
  || "ok!"
));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM