vanilla javascript 中是否有像 p5.js 这样的地图函数?

Plz*_*elp 3 javascript p5.js

在p5.js中,有一个名为map()的函数,它将某个范围内的值映射到另一个范围内的另一个值。vanilla javascript 中是否有类似的方法?

Ilm*_*nen 7

不,JavaScript 中没有开箱即用的类似功能,但编写您自己的代码很容易:

// linearly maps value from the range (a..b) to (c..d)
function mapRange (value, a, b, c, d) {
    // first map value from (a..b) to (0..1)
    value = (value - a) / (b - a);
    // then map it from (0..1) to (c..d) and return it
    return c + value * (d - c);
}
Run Code Online (Sandbox Code Playgroud)

另外,P5.js是用JavaScript编写的,因此它的map()功能本质上JavaScript。P5.js 是开源的,该函数可以在这里map()找到:

var newval = (n - start1) / (stop1 - start1) * (stop2 - start2) + start2;
Run Code Online (Sandbox Code Playgroud)