简体   繁体   中英

How Can I Re-scale An Array To A Range Of Values in Javascript?

I'd like to re-scale a two dimensional array with a function where the min and max input range and min and max output range can be specified. For example, we want to re-scale the values 0 to 8 to 0 to 1.

const scale = (num, in_min, in_max, out_min, out_max) => {
    return (num - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;

var array_scaled = orignal_array.map(scale(num, 0, 8, 0, 1));

}

The code produces the following error: ReferenceError: num is not defined

What is the correct syntax to call the scale function from within map?

我猜 map 的参数必须是一个函数,即:

var array_scaled = orignal_array.map(num=>scale(num, 0, 8, 0, 1));

Array.prototype.map() accepts a callback function as its first argument.

It looks like num is not defined as the current element of the array to the callback function scale()

Try var array_scaled = orignal_array.map(array_num => scale(array_num, 0, 8, 0, 1));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM