有兩個功能
const clamp = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));
const map = (x, a, b, c, d, clamp) => (x - a) * (d - c) / (b - a) c
const c = map(-50, 0, 1, 0, 100)
const _c = clamp(c, 0, 1)
console.log(_c, c)
有什么辦法可以將這兩個功能結合起來,比如
const _c = map(-50, 0, 1, 0, 100, {clamp: true})
這樣我就不需要從 map 函式中復制引數來獲取引數范圍內的新值。
uj5u.com熱心網友回復:
這很簡單,只需創建一個函式,然后依次執行原始 map 函式,如果clamp引數是,true則計算并回傳它。檢查下面的代碼。
const map(x, a, b, c, d, clamp) {
const map_result = (x - a) * (d - c) / (b - a) c;
if (clamp) {
const clamp_result = Math.max(Math.min(map_result, Math.max(a, b)), Math.min(a, b));
return clamp_result
}
return map_result;
}
你可以這樣使用它:
const _c = map(-50, 0, 1, 0, 100, true)
uj5u.com熱心網友回復:
您可以將該函式傳遞給clamp 函式并在其中使用它。或者,如果函式位于相同的位置,您可以在鉗位函式中呼叫它
const map = (x, a, b, c, d, clamp) => (x - a) * (d - c) / (b - a) c
const _map = (x, a, b, c, d, map) => Math.max(Math.min(map(x, a, b, c, d), Math.max(a, b)), Math.min(a, b));
const a = _map(-50, 0, 1, 0, 100, map)
console.log(a)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/394559.html
標籤:javascript 功能
