JavaScript 中最紧凑的方法是什么,可以在一系列值中强制值

What is the most compact way in JavaScript to force a value in a range of values?

本文关键字:一系列 是什么 JavaScript 方法      更新时间:2023-09-26

我有一个简单的 2 行过程,就像

if ( bgwidth < 0 ) { bgwidth = 0; }
else if ( bgwidth > 100 ) { bgwidth = 100; }

我想知道最紧凑的方法是什么。位移运算符有办法吗?:)

Math.min()Math.max()可能会做到这一点:

Math.min(Math.max(0, bgwidth), 100);

为了可读性:

function fitBetween(value, min, max) {
  return Math.min(Math.max(min, value), max);
}