javascript - 在 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,...?}
我不知道为什么会这样,数学上我确信平庸的公式。
解决方案
您需要交出最小值(含)和最大值(不含)和实际值才能获得颜色。
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));
推荐阅读
- python - 尝试将浮点操作数和度数符号组合到同一个变量中
- c++ - Why does my custom allocator preform proportional to malloc?
- ios - URLSession dataTask / uploadTask splitting large uploads into multiple requests
- python - 数据帧值预处理 - readexcel 在导入期间在值中删除撇号或在导入后将字符串转换为 int 值的其他方式
- clojure - Clojure 反向链接事实
- javascript - JavaScript 当前日期和特定日期之间的天数,Date() 奇怪的行为
- javascript - 正则表达式允许单词之间的标点符号和空格
- ios - 调用popToViewController后如何清除视图中的文本框
- javascript - 在反应中将道具从父组件传递给子组件
- python - python中使用numpy的频谱图