Why not build the chart by using Chart.js?

Not displayed column in the chart.

<!DOCTYPE html>
<html lang="en">
the <head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
</head>
the <body>
<button>
Start
</button>
 <canvas id='chart'></canvas>
 <legend for="canvas"></legend>


 <script src="main.js"></script>
</body>
</html>


let button = document.querySelector('button');


button.onclick = function(){
 let wordsLength = [];
 let answer = prompt('Enter a sentence');
 answer = answer.replace(/[^\w\s]/gi, "");
 let words = answer.split(' ');

 for (let i = 0; i < answer.length - 1; i++){
 let word = words[i];
wordsLength.push(word.length);
}
 var ctx = document.getElementById('chart');
 var myChart = new Chart(ctx, {
 type: 'bar',
 data: {
 labels: words,
 datasets: [{
 label: 'Number of letters',
 data: wordsLength,
 backgroundColor: [
 'rgba(255, 99, 132, 0.2)'
],
 borderColor: [
 'rgba(255, 99, 132, 1)'
],
 borderWidth: 1
}]
},
 options: {
 scales: {
 yAxes: [{
 ticks: {
 beginAtZero: true
}
}]
}
}
});
}
March 23rd 20 at 19:16
1 answer
March 23rd 20 at 19:18
Solution
Because the error. Because I'm trying to read property from undefined. Get udnefined because pulling a non-existent element of the array. Because the cycle does more iterations than the array elements. Because instead of the length of the array of words to compare the value of the loop counter with the length of the string from which words cut.

Change

for (let i = 0; i < answer.length - 1; i++)

on

for (let i = 0; i < words.length; i++)

UPD. https://jsfiddle.net/h0xm9ysc/
changed, however, the columns still do not appear - max.Denesik91 commented on March 23rd 20 at 19:21
Well, I have everything displayed. I think I you believe, that you were something changed, and if changed, then changed where it is necessary and what is necessary? No, it is not. Go to jsfiddle, codepen , or any other sandbox, collect demo, throw a link here. Then continue the conversation.

UPD. There's no way? Well, added in the answer a link to a demo. Then think for yourself. - dina commented on March 23rd 20 at 19:24

Find more questions by tags Chart.jsJavaScript