ChartJS 为什么每一串数字都有NaN

5n0oy7gb  于 2023-04-20  发布在  Chart.js
关注(0)|答案(1)|浏览(148)
var countsTest = [{"roundId":19,"scores":[{"scoreId":181,"score":2,"holePar":3,"name":"Birdie","color":"#77ACD8"},{"scoreId":182,"score":4,"holePar":3,"name":"Bogie","color":"#FBD59C"},{"scoreId":183,"score":4,"holePar":3,"name":"Bogie","color":"#FBD59C"},{"scoreId":184,"score":2,"holePar":3,"name":"Birdie","color":"#77ACD8"},{"scoreId":185,"score":3,"holePar":3,"name":"Par","color":"#eee"},{"scoreId":186,"score":2,"holePar":3,"name":"Birdie","color":"#77ACD8"},{"scoreId":187,"score":3,"holePar":3,"name":"Par","color":"#eee"},{"scoreId":188,"score":3,"holePar":3,"name":"Par","color":"#eee"},{"scoreId":189,"score":3,"holePar":3,"name":"Par","color":"#eee"}],"roundDate":"2023-03-04T00:00:00.000+01:00","total":26,"barChartArray":[2,4,4,2,3,2,3,3,3],"dateWithoutTimeOfDay":"2023-03-04"}];

const counts = {};

        for (let i = 0; i < countsTest.length; i++) {
          const num = parseInt(countsTest[i]);
          counts[num] = counts[num] ? counts[num] + 1 : 1;
        }

        const oldChart = chart.chart;
        if (oldChart) {
          oldChart.destroy();
        }

        const myChart = new Chart(chart, {
          type: 'bar',
          options: {
            responsive: true,
            maintainAspectRatio: false,
            indexAxis: 'y',
            scales: {
              x: {
                stacked: true,
                display: false
              },
              y: {
                stacked: true,
                display: false
              }
            },
            plugins: {
              legend: {
                display: false
              }
            }
          },
          data: {
            labels: ["Score"],
            datasets: [{
              data: [counts[2] || 0],
              backgroundColor: "#77ACD8"
            }
            ,{
              data: [counts[3] || 0]

            },{
              data: [counts[4] || 0],
              backgroundColor: "#FDC26A"
            },{
              data: [counts[5] || 0],
              backgroundColor: "#FCAE37"
            },{
              data: [counts[6] || 0, counts[7] || 0, counts[8] || 0, counts[9] || 0, counts[10] || 0],
              backgroundColor: "#FCAE37"
            }
            ]
          }
        });
        chart.chart = myChart;
<div class="container-fluid">
    <canvas id="myChart"></canvas>
</div>

我是一个完全的JavaScript初学者,我有一个springboot项目为discgolf,并有一个 accordion 为每一个课程,它打开了所有轮发挥为用户。我创建n水平条形图和传递一轮JavaScript使用图表js呈现图表。
html(来自th:each的舍入)

<div class="container-fluid">
    <canvas th:data-counts="${round}"></canvas>
</div>

我的图表JavaScript

const charts = document.querySelectorAll('[data-counts]');
      charts.forEach(chart => {
        const countsTest = chart.getAttribute('data-counts').split(',');

        const counts = {};

        for (let i = 0; i < countsTest.length; i++) {
          const num = parseInt(countsTest[i]);
          counts[num] = counts[num] ? counts[num] + 1 : 1;
        }

        console.log(countsTest); // Log the countsTest array
        console.log(counts); // Log the counts object

        const oldChart = chart.chart;
        if (oldChart) {
          oldChart.destroy();
        }

        const myChart = new Chart(chart, {
          type: 'bar',
          options: {
            responsive: true,
            maintainAspectRatio: false,
            indexAxis: 'y',
            scales: {
              x: {
                stacked: true,
                display: false
              },
              y: {
                stacked: true,
                display: false
              }
            },
            plugins: {
              legend: {
                display: false
              }
            }
          },
          data: {
            labels: ["Score"],
            datasets: [{
              data: [counts[2] || 0],
              backgroundColor: "#77ACD8"
            }
            ,{
              data: [counts[3] || 0]

            },{
              data: [counts[4] || 0],
              backgroundColor: "#FDC26A"
            },{
              data: [counts[5] || 0],
              backgroundColor: "#FCAE37"
            },{
              data: [counts[6] || 0, counts[7] || 0, counts[8] || 0, counts[9] || 0, counts[10] || 0],
              backgroundColor: "#FCAE37"
            }
            ]
          }
        });
        chart.chart = myChart;
      });

控制台中的舍入数据

['Round{roundId=19', ' course=Course{id=1', " name='Legende'", ' holes=[Hole{holeId=37', ' number=1', ' par=3}', ' Hole{holeId=38', ' number=2', ' par=3}', ' Hole{holeId=39', ' number=3', ' par=3}', ' Hole{holeId=40', ' number=4', ' par=3}', ' Hole{holeId=41', ' number=5', ' par=3}', ' Hole{holeId=42', ' number=6', ' par=3}', ' Hole{holeId=43', ' number=7', ' par=3}', ' Hole{holeId=44', ' number=8', ' par=3}', ' Hole{holeId=45', ' number=9', ' par=3}]', ' par=27', ' record=-2', ' courseAverage=27.238095238095237}', ' scores=[Score{scoreId=181', ' score=2', ' holePar=3', " name='Birdie'", " color='#77ACD8'}", ' Score{scoreId=182', ' score=4', ' holePar=3', " name='Bogie'", " color='#FBD59C'}", ' Score{scoreId=183', ' score=4', ' holePar=3', " name='Bogie'", " color='#FBD59C'}", ' Score{scoreId=184', ' score=2', ' holePar=3', " name='Birdie'", " color='#77ACD8'}", ' Score{scoreId=185', ' score=3', ' holePar=3', " name='Par'", " color='#eee'}", ' Score{scoreId=186', ' score=2', ' holePar=3', " name='Birdie'", " color='#77ACD8'}", ' Score{scoreId=187', ' score=3', ' holePar=3', " name='Par'", " color='#eee'}", ' Score{scoreId=188', ' score=3', ' holePar=3', " name='Par'", " color='#eee'}", ' Score{scoreId=189', ' score=3', ' holePar=3', " name='Par'", " color='#eee'}]", ' roundDate=2023-03-04 00:00:00.0', ' total=26', ' barChartArray=[2', ' 4', ' 4', ' 2', ' 3', ' 2', ' 3', ' 3', ' 3]}']

老实说,我不知道分数是如何到达条形图的,但它的工作,但我仍然得到一个NaN为每一轮的分数之一。屏幕截图显示了正确的分数卡,但每个图表都是错误的一个数字,它还显示了控制台中的输出。正如你所看到的,有3:记分卡中为2,但条形图上只有2。{2:二、三、四、四NaN:81})
那么我如何在一轮中使用scores对象来创建图表呢?所以使用score.score或barChartArray来创建数字,标签score.name和颜色score.color

q7solyqu

q7solyqu1#

所以这是我的json,我最终做的是将完整的rounds列表传递给我的javascript,然后在thymeleaf循环中,我通过th:roundId传递roundId。
thymeleaf循环中的html

<div class="container-fluid">
     <canvas th:roundId="${round.roundId}" th:id="myChart"></canvas>
</div>

通过完整的回合列表

<script th:inline="javascript">
    let rounds = /*[[${roundsJsonNode}]]*/ {};
</script>

然后在javascript中,我使用getRoundsById方法获取round by id,并为每一轮创建一个条形图。

function getRoundById(rounds, roundId) {
      return rounds.find((round) => round.roundId === Number(roundId));
    }

    

    const charts = document.querySelectorAll('[roundId]');
      charts.forEach(chart => {
        const getRound = chart.getAttribute('roundId').split(',');
        const roundData = getRoundById(rounds, getRound);

        const scoreCount = roundData.scores.length;
        const scoreData = {};

        for (let i = 0; i < scoreCount; i++) {
          const score = roundData.scores[i];
          if (!scoreData[score.name]) {
            scoreData[score.name] = {
              count: 0,
              color: score.color,
              score: score.score,
            };
          }
          scoreData[score.name].count += 1;
        }

        const datasets = [];
        Object.entries(scoreData).forEach(([name, data]) => {
          datasets.push({
            label: name,
            backgroundColor: data.color,
            data: [data.count],
            score: data.score, // add score value to dataset object
          });
        });

        datasets.sort((a, b) => a.score - b.score); // sort datasets by score value

        const myChart = new Chart(chart, {
          type: 'bar',
          options: {
            responsive: true,
            maintainAspectRatio: false,
            indexAxis: 'y',
            scales: {
              x: {
                stacked: true,
                display: false,
              },
              y: {
                stacked: true,
                display: false,
              },
            },
            plugins: {
              legend: {
                display: false,
              },
            },
          },
          data: {
            labels: [''],
            datasets,
          },
        });
      });

相关问题