首页 > 解决方案 > 在 Javascript 中的范围内制作标量

问题描述

我有未来几天的天气温度。我想将所有值映射到{0,1,2,3,4}

为此,我正在尝试:

let scale = Math.round((todayTemp / maxTemp) * 5) - 1

  markersIcons[0] = 'blue'
  markersIcons[1] = 'purple'
  markersIcons[2] = 'green'
  markersIcons[3] = 'yellow'
  markersIcons[4] = 'red'

markersIcons[scale]

我有未定义的结果。如此多不可预测的结果:{-1,5,...?}

我不知道为什么会这样,数学上我确信平庸的公式。

标签: javascript

解决方案


您需要交出最小值(含)和最大值(不含)和实际值才能获得颜色。

const
    COLORS = ['blue', 'purple', 'green', 'yellow', 'red'],
    getColor = (min, max, value) => COLORS[Math.floor(COLORS.length * (value - min) / (max - min))];

console.log(getColor(-10, 40, -10));
console.log(getColor(-10, 40, 0));
console.log(getColor(-10, 40, 10));
console.log(getColor(-10, 40, 20));
console.log(getColor(-10, 40, 30));
console.log(getColor(-10, 40, 39));


推荐阅读