0

This question relates directly to Highcharts, but is really more pertinent to general JavaScript and loops.

My code is as follows:

load:function(){
  var series0 = this.series[0];
  var series1 = this.series[1];
    setTimeout(function(){
      series0.addPoint(myjson.list[0].value);
      series1.addPoint(myjson.list[1].value);
    }, 1000);
} 

I wanted to first show an example of code that works. With Highcharts, this code gathers the designated indexes from my JSON lists and appends them to my existing chart.

When attempting a for loop to perform the same action however I end up bungling it.

My for loop attempt:

var update = [];
   for (i = 0; i < myjson.list.length; i++){
       update[i] = this.series[i];
       update.addPoint(myjson.list[i].Printvalue);
   }

There is clearly something wrong with my loop logic, and yet I am unable to figure out exactly what. When running this loop code I get an error of:

update.addPoint is not a function

My biggest guess is it has to do with the way I am handling the this instance.

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
Jason Chen
  • 2,487
  • 5
  • 25
  • 44
  • 1
    in the code above update is an array. You are trying to call an addPoint method on the array you need to be calling it on a value inside that array. `update[i].addPoint(myjson.list[i].Printvalue)` – Thomas Devries Jul 10 '17 at 20:16

1 Answers1

2

In your example, update is a normal array because you declare it with var update = []. The normal JavaScript array does not have a function called addPoint.

I'm not sure what it should be, but it definitely doesn't have anything to do with your use of this.

If the items in this.series include addPoint, you might want to use this:

update[i].addPoint(myjson.list[i].Printvalue);

Note the [i] after update.

samanime
  • 25,408
  • 15
  • 90
  • 139
  • exactly what I was about to put in the answer, way to go – AGE Jul 10 '17 at 20:16
  • EDIT: Argh. There is another problem. My function works, but not when incorporating a `setTimeout`. I get a `cannot read property 2 of undefined`, meaning there is some issue with the `setTimeout` function and indexes. – Jason Chen Jul 10 '17 at 20:26
  • EDIT: Nvm. Figured it out with the help of this example(https://stackoverflow.com/questions/5226285/settimeout-in-for-loop-does-not-print-consecutive-values) – Jason Chen Jul 10 '17 at 20:31