Javascript 获取两个值之间的数字
有没有一种简单的方法可以得到两个值或这些值之间的数字? 例如:Javascript 获取两个值之间的数字,javascript,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,值)); 但是有没有一种更有效和/或更优雅的方法来做到这一点呢?这可能有些过分,但这里有一个可重
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,值));
但是有没有一种更有效和/或更优雅的方法来做到这一点呢?这可能有些过分,但这里有一个可重用的解决方案:
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));
功能夹持器(最小值、最大值){
返回函数(v){
返回v>max?max:(v
小提琴:不,没有比这更好的方法了。这可能是我的选择。如果你真的想要一个替代方案,你可以这样使用:
value > 100 ? 100 : value < 10 ? 10 : value;
clamp(value, 10, 100);
那么就这样使用它:
value > 100 ? 100 : value < 10 ? 10 : value;
clamp(value, 10, 100);
詹姆斯是对的。查看详情
/**
* 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);
};
这叫夹紧。在我看来,你的方法非常高效/优雅,但你可以将其转化为一个函数。
value100?100:value
@James McLaughlin,谢谢,我不知道这个名字,现在谷歌向我显示的结果比以前多得多;-)@JamesMcLaughlin,把它变成问题