JavaScript Array-Push?

Viewed 43

I'm using charts.js, where I want to add one datarow per minute. Hence to avoid a complete redraw, Im using some ajax and just pushing a new element to the chart.

Pushing VALUES works fine, however, pushing to the label-array shows very strange behaviour. I'v now tried everything from a simple push upto iteratively cloning the whole array, copy all values, replacing the whole array... The result is still the same.

The added element seems to be always end up with index 0, therefore ending up left in the chart, rather than on the right side.

Upon initial pageload, the data that is existing is loaded as a json-array, which works as expected, for example:

var labels = ["16:00", "16:01", "16:02"]

Now, using some ajax, I retrieve a new Dataset for 16:03. Pushing that label to the array like this:

...
labels.push("16:03");
console.log(labels);
...

and inspecting it in the browser afterwards leads to the following strange view:

  • The stringified representation looks as expected:

    (4) ["16:00", "16:01", "16:02", "16:03"]
    
  • But when expanding the view in chrome, the result is:

    0: "16:03"
    1: "16:00"
    2: "16:01"
    3: "16:02"
    

So, iterating the array by using index-values obviously leads to a different result than using .toString(). I have no idea what is happening here. I'm mainly confused, why the stringified version looks different than the actual drill down on indexes?

Running a vanilla-example of these steps leads to the desired result. So it has to do something with the "context" of that array. But I have no idea where to start digging ;)

Here's a screenshot

enter image description here

edit: Following the example over here, it should work like that... https://www.chartjs.org/docs/latest/developers/updates.html

1 Answers

Comment of @CBroe made me figure it out:

  • Uppon initial loading, I did not outline the labels explicit, because there i'm having whole objects like {x:"16:00", temp="20", rain="0"} i'm feeding the datarows of chart.js with.

  • Now, when altering the label-array, chart-js seems to apply the following logic:

    • Labels-Array is a dedicated Array that EXISTS but is empty if not explicit defined.
    • In the Getter of that array, Any Labels derived from data-objects are appended to the array.

hence, pushing to the actual array starts with index "0" if it's inititially empty. But looking at the result of the getter then delivers the static array + any required label derived from the data objects given.

Now outlining the labels-array explicit as well, this resolves the issue.

Related