实现说明
除了函数 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));