获取两个值之间的数字

时间:2014-08-25 18:12:07

标签: javascript

是否有一种简单的方法可以获得两个值或这些值之间的数字? 例如:

min: 10, max: 100
(in -> out)

   1 -> 10
   5 -> 10
  10 -> 10
  50 -> 50
 100 -> 100
1000 -> 100
9999 -> 100

现在我正在使用它:

Math.max(10, Math.min(100, value)); 

但是有更高效和/或更优雅的方式吗?

3 个答案:

答案 0 :(得分:1)

这可能是矫枉过正,但这是一个可重复使用的解决方案:

function clamper(min, max) {
    return function(v) {
        return v > max ? max : (v < min ? min : v);
    };
}

var clamp = clamper(0, 100);

console.log(clamp(25));
console.log(clamp(50));
console.log(clamp(74));
console.log(clamp(120));
console.log(clamp(-300));

小提琴:http://jsfiddle.net/mx3whct6/

答案 1 :(得分:0)

不,真的没有比这更好的方法了。这可能与我的目标相同。如果您真的想要替代方案,可以使用conditional operator,如下所示:

value > 100 ? 100 : value < 10 ? 10 : value;

但是,我发现这比简单min / max更难阅读。

当然,如果你发现自己经常这样做,你可以为了简洁而自己动手:

function clamp(val, min, max) {
    return Math.max(min, Math.min(max, val));
}

然后就这样使用它:

clamp(value, 10, 100);

答案 2 :(得分:0)

詹姆斯是对的。查看this了解详情

/**
 * Returns a number whose value is limited to the given range.
 *
 * Example: limit the output of this computation to between 0 and 255
 * (x * 255).clamp(0, 255)
 *
 * @param {Number} min The lower boundary of the output range
 * @param {Number} max The upper boundary of the output range
 * @returns A number in the range [min, max]
 * @type Number
 */
Number.prototype.clamp = function(min, max) {
  return Math.min(Math.max(this, min), max);
};