如果其他基础逻辑为foreach失败,则转换



我有这个功能

const applyColor = (value) => {
        let color
        //shallow to dark
        const colors = ['#B3E5FC', '#81D4FA' ,'#4FC3F7', '#29B6F6', '#03A9F4', '#039BE5', '#0288D1']
        if(value >= 100 && value < 199){
            return {index: 1, color: colors[0]}
        }else if(value >= 200 && value < 299){
            return {index: 2, color: colors[1]}
        }else if(value >= 300 && value < 399){
            return {index: 3, color: colors[2]}
        }else if(value >= 400 && value < 499){
            return {index: 4, color: colors[3]}
        }else if(value >= 500 && value < 599){
            return {index: 5, color: colors[4]}
        }else if(value >= 600 && value < 699){
            return {index: 6, color: colors[5]}
        }else if(value >= 700){
            return {index: 7, color: colors[6]}
        }
}

我做

时正在工作
{data.map(o => <div style={{background: applyColor(o.value).color }}></div>)}

,但我试图使用循环进行重构。

let gap = 100
        const maximum = 700
        for(let i = 0; i < colors.length; i++) {
            if(value >= maximum) {
                color = {index: colors.length, color: colors[colors.length - 1]}
            }else if(value >= gap && value < gap + 99){
                color = {index: i, color: colors[i]}
            }
            gap += 100
            return color
        }

我有未定义错误的颜色,我找不到问题。任何线索?

您需要注意小于差距的值,并且需要一种一致的方法来计算索引。您当前的代码将从0开始(上一个启动 1 ),但最后一个索引将是colors.length,即7以前是6 ),所以现在6完全跳过。

使用

const applyColor = (value) => {
  const colors = ['#B3E5FC', '#81D4FA', '#4FC3F7', '#29B6F6', '#03A9F4', '#039BE5', '#0288D1']
  const step = 100,
        index = Math.max(1,Math.min(Math.floor(value / step), colors.length)); // clamp index between 1 and color.length 
  return {
    index: index ,
    color: colors[index-1]
  }
}
// testing
for(let i = 50; i<=850;i+=100){
  console.log(`applyColor(${i}) == `, applyColor(i));
}
/*for stackoverflow console*/
div.as-console-wrapper{max-height:100%}

正如其他人所提到的,我现在从0而不是1开始。

我对JavaScript并不过于熟悉,因此请原谅任何语法错误(如果这是错误的,请建议编辑)。这不能简化为:

let color
const colors = ['#B3E5FC', '#81D4FA' ,'#4FC3F7', '#29B6F6', '#03A9F4', '#039BE5', '#0288D1']
var i = Math.floor(value/100)
if (i> colors.Length) {i= colors.Length}
if (i <1) {i= 1}
return {index: i, color: colors[i - 1]}

基本上将整数划分为100如果超过7使其成为7或LT;1使其1返回颜色

最新更新