[英]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()));
}
if(typeof prog != 'number' || prog < 0){
prog = 0;
} else if (prog > 100) {
prog = 100;
}
prog
is not a number, or less than 0, set to zero right off the bat prog
不是数字,或小于0时,设定为零马上蝙蝠 prog
is greater than 100, set 100 prog
大于100,则设置为100 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));
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
,否则确保它在0
到100
之间,这似乎是您真正追求的逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.