← 中文资源

简体中文版本

Math.min 与 Math.max 把值钳到边界

Math.min/max 接受任意参数:空调用返回 Infinity/-Infinity、任一参数 NaN 会污染结果;嵌套两者构成经典 clamp,配合展开可求数组极值。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

1
5
empty min: Infinity
empty max: -Infinity
with NaN: NaN
range: 18 to 25
clamp: 10 0 5

实现说明

除了函数 clamp,文件里再无其他定义。

使用要点

  • 每一步打印都带着自己的标签:empty min:、empty max:、with NaN:。

常见问题

复制和运行之间有安装步骤吗?

没有。从复制到运行之间没有别的要做。 文件在加载时定义 clamp。

主要签名是 function clamp(value, lo, hi)

核心语句

return Math.min(Math.max(value, lo), hi);

代码示例

// Math.min 和 Math.max 接受任意参数,返回最值
console.log(Math.min(3, 1, 4, 1, 5));
console.log(Math.max(3, 1, 4, 1, 5));

// 空参数:min 返回 Infinity,max 返回 -Infinity
console.log("empty min:", Math.min());
console.log("empty max:", Math.max());

// 任一参数为 NaN,结果就是 NaN(不静默忽略)
console.log("with NaN:", Math.min(1, NaN, 3));

// 展开数组做边界检查
const temps = [21, 19, 23, 18, 25];
console.log("range:", Math.min(...temps), "to", Math.max(...temps));

// 经典 clamp:用 min 和 max 把值限制在区间内
function clamp(value, lo, hi) {
  return Math.min(Math.max(value, lo), hi);
}
console.log("clamp:", clamp(15, 0, 10), clamp(-3, 0, 10), clamp(5, 0, 10));