FMa*_*008 3 javascript php math
在PHP(或任何类似的语言)中,有更好的替代方法:
if(x >= 200 && x <= 299){
return 'ok';
}
Run Code Online (Sandbox Code Playgroud)
我的目标是验证数字是否在2xx代码的范围内(对于HTTP请求).我不喜欢double-if子句,因为我必须定义范围的结束,并且由于某种原因,在进行各种自动验证时这是不实际的.
在PHP(或任何类似的语言),是否有更好的替代...
在我看来,没有.
你的代码:
if (x >= 200 && x <= 299) {
return 'ok';
}
Run Code Online (Sandbox Code Playgroud)
非常易读并清楚地定义了要检查的内容.
如果你想要一个声明,你肯定会在三个月后忘记你的意思:
if(2 == (int)floor(x / 100)) ...
Run Code Online (Sandbox Code Playgroud)
如果没有别的,为了便于阅读,请将其包装在描述它的函数中:
function isHttpSuccess(status) {
return 2 == (int)floor(x / 100);
}
Run Code Online (Sandbox Code Playgroud)
如果你有一个功能,你可以使用返回'技巧':
function getStatus(x) {
if(x < 200) return 'status 1xx';
if(x < 300) return 'status 2xx'; // will only get executed if x >= 200 as well
// otherwise already returned '1xx'
...
}
Run Code Online (Sandbox Code Playgroud)