简体   繁体   中英

Javascript dynamically generated variables with 'this'

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM