You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何基于JSON数组状态值通过条件语句设置对应颜色

你可以直接通过数组映射的方式实现匹配,不需要写冗余的条件分支,实现代码如下:

// 建立状态值和颜色配置键的对应关系
const statusToColorKey = {
  A: 'yellow',
  B: 'green',
  C: 'gray'
};

// 遍历状态数组生成对应的背景色数组
const functionChartConfig = {
  datasets: [
    {
      backgroundColor: functionStatus.map(status => chartColors[statusToColorKey[status]]),
      data: functionInfo
    }
  ]
};

如果确实需要用条件语句实现,也可以写成如下形式:

const functionChartConfig = {
  datasets: [
    {
      backgroundColor: functionStatus.map(status => {
        if (status === 'A') return chartColors.yellow;
        if (status === 'B') return chartColors.green;
        if (status === 'C') return chartColors.gray;
        // 异常状态默认返回灰色,可自行调整
        return chartColors.gray;
      }),
      data: functionInfo
    }
  ]
};

注意:你原来的变量名用了Function,这是JavaScript内置的构造函数名,作为自定义变量名使用会有语法冲突风险,建议替换为其他自定义名称比如上面示例的functionChartConfig。

内容的提问来源于stack exchange,提问作者ssksksks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 22:24:00