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

SpringBoot飞盘高尔夫项目中Chart.js图表出现NaN及统计错误的解决

解决飞盘高尔夫项目中Chart.js横向条形图NaN与统计错误问题

1. 确保Thymeleaf正确传递scores数据

直接用Thymeleaf内联JS把后端的scores数组转成合法JSON,避免手动拼接导致格式错误:

<script th:inline="javascript">
  // 从后端获取Round对象的scores数组
  const rawScores = /*[[${round.scores}]]*/ [];
  // 预处理数据:强制转分数为数字,过滤无效值避免NaN
  const validScores = rawScores.map(item => ({
    score: Number(item.score),
    name: item.name,
    color: item.color
  })).filter(item => !isNaN(item.score));
</script>

2. 正确统计分数出现次数

遍历预处理后的数组,完整统计每个分数的数量:

// 统计分数频次
const scoreStats = {};
validScores.forEach(item => {
  const score = item.score;
  scoreStats[score] = (scoreStats[score] || 0) + 1;
});

// 整理成Chart.js所需格式
const labels = Object.keys(scoreStats).map(Number);
const dataValues = Object.values(scoreStats);
// 匹配每个分数对应的颜色(取该分数首次出现的color)
const backgroundColors = labels.map(score => {
  return validScores.find(item => item.score === score).color;
});

3. 初始化Chart.js横向条形图

配置横向条形图,确保数据与标签对应:

const ctx = document.getElementById('scoreChart').getContext('2d');
new Chart(ctx, {
  type: 'bar',
  data: {
    labels: labels,
    datasets: [{
      label: '分数统计',
      data: dataValues,
      backgroundColor: backgroundColors,
      borderWidth: 1
    }]
  },
  options: {
    indexAxis: 'y', // 设置为横向条形图
    scales: {
      x: {
        beginAtZero: true,
        title: {
          display: true,
          text: '次数'
        }
      },
      y: {
        title: {
          display: true,
          text: '分数'
        }
      }
    }
  }
});

关键注意点

  • 强制转换score为数字:后端传递的score可能是字符串,直接使用会导致Chart.js解析出NaN,必须转换并过滤无效值。
  • 完整遍历scores数组:避免Thymeleaf循环时遗漏数据,直接使用后端传递的完整数组统计更可靠。
  • 颜色匹配:通过分数关联对应color,保证条形颜色与score的color一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 07:52:09