Javascript / jQuery - map a range of numbers to another range of numbers

后端 未结 8 1477

In other programming languages such as processing, there is a function which allows you to convert a number that falls within a range of numbers into a number within a diffe

相关标签:
8条回答
  • 2020-12-02 18:17

    For a general purpose mapping function, which is what the OP asked for, go here:

    http://rosettacode.org/wiki/Map_range#JavaScript

    0 讨论(0)
  • 2020-12-02 18:19

    well its simple math. well you have two ranges range1 = [a1,a2] and range2 = [b1,b2] and you want to map a value s in range one to a value t in range two. so this is the formula. t = b1 + (s-a1)*(b2-b1)/(a2-a1) in js it will be.

    var mapRange = function(from, to, s) {
      return to[0] + (s - from[0]) * (to[1] - to[0]) / (from[1] - from[0]);
    };
    
    var range = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    for (var i = 0; i < range.length; i++) {
      range[i] = mapRange([0, 10], [-1, 0], range[i]);
    }
    
    console.log(range);
    
    0 讨论(0)
提交回复
热议问题