Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

How to access javascript array values within a setinterval function

How can I access the series data from within the function defined in setinterval. When I try to access any of the values, or even the array length, it says undefined.

events: {
                load: function() {

                    // set up the updating of the chart each second
                    var series0 = this.series[0];
                    var series1 = this.series[1];
                    var series2 = this.series[2];
                    var series3 = this.series[3];
                    setInterval(function() {
                        var y = $.ajax({url: "/index.php/control/fetch/<?php echo $uid; ?>",async: false}).responseText;
                            y = y.split(" ");
                        var x = parseInt(y[0]);
                        //alert("x = " + series0[0]);
                        //alert("len is " + parseInt(series0.length));
                        series0.addPoint([x, parseFloat(y[1])], true, true);
                        series1.addPoint([x, parseFloat(y[2])], true, true);
                        series2.addPoint([x, parseFloat(y[3])], true, true);
                        series3.addPoint([x, parseFloat(y[4])], true, true);

                    }, 5000);
                }
            }

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to make a reference to this outside the callback function in setInterval. Something like this:

load : function() {
 ...
 var _self = this;
 setInterval(function() {
   console.log( _self.series );
 }, 5000);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...