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
相关产品推荐
相关产品推荐

