简体   繁体   English

如何在javascript中优化此if-else语句

[英]How to optimize this if-else statement in javascript

I have a piece of javascript code like this 我有一段这样的JavaScript代码

        if(prog > 100)
          prog = 100;
        else if(prog <0)
          prog = 0;
        else if(typeof prog != 'number')
          prog = 0;

It looks bad and ugly. 看起来很丑陋。 Is there some cooler way to write this in javascript? 有一些更酷的方法可以用javascript编写吗?

prog = Math.max(0, Math.min(100, typeof prog == 'number' ? prog : 0));

How about this: 这个怎么样:

 foo = typeof foo == "number" ? foo : 0;
 foo.constrain(0, 100);

Which would simply require this to be defined: 只需将其定义即可:

Number.prototype.constrain = function(min, max) {
  return Math.min(max, Math.max(min, this.valueOf())); 
}

prog = (prog > 100 ? 100 : (prog<0 || (typeof prog != 'number') ? 0 : prog)); prog =(prog> 100?100:(prog <0 ||(typeof prog!='number')?0:prog));

jsfiddle jsfiddle

if(typeof prog != 'number' || prog < 0){
    prog = 0;
} else if (prog > 100) {
    prog = 100;
}
  • if prog is not a number, or less than 0, set to zero right off the bat 如果prog不是数字,或小于0时,设定为零马上蝙蝠
  • else if prog is greater than 100, set 100 否则,如果prog大于100,则设置为100
  • anything else, it leaves it alone 别的,它一个人呆着

the issue was you were evaluating a variable as a number without knowing that it's a number (since you placed the typeof check last). 问题是您正在将变量评估为数字而不知道它是数字(因为您将typeof检查放在最后)。 if i were to pass foo to prog , you'd be evaluating 2 times before checking the type. 如果我要将foo传递给prog ,则在检查类型之前您将进行两次评估。 also, you were evaluating two conditions for the same output of 0 , better merge them. 同样,您正在为相同的0输出评估两个条件,更好地合并它们。

JS does not evaluate the OR further when it sees a TRUE in the condition. 当JS在条件中看到TRUE时,不会进一步评估OR likewise can be said for the AND when it sees a FALSE . AND看到FALSE时,也可以这样说。

Really you should test the type first: 确实应该先测试类型:

if ( typeof prog != 'number' || prog < 0 )
   prog = 0;
else if( prog > 100 )
   prog = 100;

Double ternary: 双三元:

prog = typeof prog != 'number'?0:prog;
prog = (prog>100)?100:((prog<0)?0:prog);

Here is my take. 这是我的看法。 It is functionally equivalent, and concise, but not the legible when you come back to the code 12 months from now. 从功能上讲,它是简洁的,但是从现在起12个月后返回代码时,它并不清晰。

prog = (typeof prog != 'number' || prog < 0 ? 0 : (prog > 100 ? 100 : prog));

UPDATE 更新

Here are a couple other ways to do this. 这是执行此操作的其他几种方法。

prog = (typeof prog != 'number' ? 0 : Math.max(0,Math.min(prog, 100)));
prog = (typeof prog != 'number' || prog < 0 ? 0 : Math.min(prog, 100));

I think the first of these two is probably the easiest to understand. 我认为这两个中的第一个可能是最容易理解的。 Basically, if it isn't a number it sets it to 0 , else it makes sure it is between 0 and 100 which seems to be the logic you are really going after. 基本上,如果不是数字,则将其设置为0 ,否则确保它在0100之间,这似乎是您真正追求的逻辑。

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

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