检查编号是否在目标编号范围内

时间:2015-12-18 13:15:06

标签: javascript

我想查看一个数字是否在目标数字的4之内。

目前我通过以下方式执行此操作:

DEMO:https://jsfiddle.net/o0b99yys/

var targetNum = 32;
var newNum = 31;

if ((newNum > (targetNum + 4)) || (newNum < (targetNum - 4))) {
  alert('Error: number must be within 4 or target');
} else {
  alert('Success: number is within 4 or target');
}
这似乎有点业余。有更清洁,更专业的方式吗?

3 个答案:

答案 0 :(得分:3)

此解决方案看起来更好:

var targetNum = 32;
var newNum = 31;

if (Math.abs(targetNum - newNum) > 4) {
  alert('Error: number must be within 4 or target');
} else {
  alert('Success: number is within 4 or target');
}

答案 1 :(得分:1)

&#13;
&#13;
    var targetNum = 32,
        newNum = 31,
        target_range_max = targetNum + 4,
        target_range_min = targetNum - 4;

    if ( target_range_min <= newNum && newNum <= target_range_max ) {
     alert('Success: number is within 4 or target');
    } else {
     alert('Error: number must be within 4 or target');
    }
&#13;
&#13;
&#13;

答案 2 :(得分:0)

如果您想要对该表达式进行简化版本,请尝试此操作:

&#13;
&#13;
var myNum = 32;
var newNum = 31;

Math.abs(myNum-newNum)>4 ? alert('Error: number must be within 4 or target') : alert('Success: number is within 4 or target');
&#13;
&#13;
&#13;