ChartJS报错:Uncaught SyntaxError: Unexpected number 求助
Hey there, let's break down exactly what's causing that frustrating syntax error in your Chart.js code.
The Uncaught SyntaxError: Unexpected number error is directly tied to the leading zeros in your dataset values (like 08.212, 07.514).
Here's the root cause: In JavaScript, numbers that start with a 0 are automatically treated as octal (base-8) numbers. But octal number systems only use digits 0-7—so when the parser hits values like 08 or 09, it throws an error because those digits aren't valid in octal.
Fix Steps
To resolve this, you just need to remove the leading zeros from all your numeric values. Alternatively, you could wrap them in quotes to treat them as strings (Chart.js will still parse them correctly as numbers behind the scenes), but removing the zeros is the cleanest fix.
I've also cleaned up a duplicate spanGaps property in your options object to avoid any potential odd behavior.
Corrected Code
<body> <div class="chartjs-wrapper"> <canvas id="line-chart" height="100px"></canvas> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script> <script> new Chart(document.getElementById("line-chart"), { type: 'line', data: { labels: [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40], datasets: [{ data: [8.212,7.514,7.334,7.214,6.986,7.367,7.225,7.619,7.090,7.148,7.090,7.684,7.890,7.132,7.234,7.065,7.033,7.110,8.262,7.150,7.122,6.878,7.864,7.295,7.235,9.855,9.176,9.498,8.163,7.395,7.369,7.230,7.065,7.365,7.024,7.276,7.275,7.405,7.120], label: "Lap Data", spanGaps: false, borderColor: "#3e95cd", fill: false }] }, options: { title: { display: true, spanGaps: true } } }); </script> </div> </body>
Quick Tip for Future
When pulling numeric data from MySQL into JavaScript, make sure your backend doesn't add leading zeros to numbers unless you specifically need them as strings. If you can't adjust the backend output, you can also add a quick JavaScript processing step to strip leading zeros before passing the data to Chart.js.
内容的提问来源于stack exchange,提问作者cyborgv7

