我有一个函数可以将两个值转换为一定范围内的百分比,在本例中为 15000 到 100000 之间。感觉非常笨重。有没有更简单的方式来表达这一点,更容易/更容易理解?
price2percent = (sale) => {
let price = sale.soldPrice / sale.livingArea;
// Specifically these values
price = price > 100000 ? 100000 : price;
price = price < 15000 ? 15000 : price;
return (price - 1500) / 85000;
}
最佳答案
您可以使用 Math.min
和 Math.max
来限制范围:
const adjustedPrice = Math.min(
100000, // can be no higher than 100000
Math.max(price, 15000) // can be no lower than 15000
);
return (adjustedPrice - 1500) / 85000;
另一个选项是嵌套条件,这将减少不必要的重新分配的数量,尽管它并不完全使代码更清晰:
const adjustedPrice =
price > 100000 ? 100000 :
price < 15000 ? 15000 : price
关于javascript - 短手(呃)最小最大百分比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53391448/