2👍
When you initially set up an array, the array has a specific size.
For example, an array with 3 values will look as following:
array[0] = value1
array[1] = value2
array[2] = value3
You can only assign an element to a position that already exists in the array.
For example, the following is valid:
array[2] = value4;
However, you cannot assign a value to a position that does not yet exist in the array, and is longer than the array length. The following code, therefore, will throw an index out of bounds error:
array[3] = value5;
Currently, you are trying to add a new value to your data
array using:
myLineChart.data.datasets[0].data[i] = (Math.random() * 100);
This code assumes that the array is at least the length of i
, which it isn’t, and is therefore throwing an error.
To append a new value to the end of an array, use Array.push()
. The push()
method adds one or more elements to the end of the array and also returns a new length of the array.
You code should look like the following:
myLineChart.data.datasets[0].data.push(Math.random() * 100);