javascript “未捕获的 ReferenceError:图表未定义”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20166159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:55:07  来源:igfitidea点击:

"Uncaught ReferenceError: chart is not defined"

javascriptchartshighcharts

提问by kcbaker

all,

全部,

I'm working with the following HTML/Javascript code:

我正在使用以下 HTML/Javascript 代码:

<!doctype html>
<html>
<head>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <!-- google fonts from CDN -->
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600' rel='stylesheet' type='text/css'>
    <!-- highcharts -->
    <script src="http://code.highcharts.com/highcharts.js"></script>

    <style>
        html, body {
            width: 95%;
            margin: auto;
            font-family: 'Open Sans',sans-serif;
        }
        #chart_container {
            width:100%;
            height:500px;
        }
    </style>
</head>
<body>
    <h1>Live Data</h1>
    <div id="chart_container">

    </div>
</body>
<script type="text/javascript">
    $(document).ready(function() {
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'chart_container',
                defaultSeriesType: 'line',
                events: {
                    load: getBirds
                }
            },
            title: {
                text: 'DRHW Live Data Stream'
            },
            xAxis: {
                type: 'datetime',
                tickPixelInterval: 150,
                maxZoom: 20 * 1000
            },
            yAxis: {
                title: {
                    text: 'Count Observed'
                }
            },
            series: [
            ],
            legend: {
                layout: 'horiztonal',
                align: 'center'
            }
        });
        function getBirds() {
            var now = new Date();
            var et = now.getTime() / 1000; //PHP TS
            var st = et - 10; //30 seconds prior in PHP
            console.log(chart);
            if (chart.series.length > 0) {
                var series = chart.series[0];
                var length = series.length + 1;
                var shift = series.data.length > 20;
            }
            $.getJSON("https://path/to/json&callback=?", function(result) {
                var data = result.data;if (data.length == 0) {
                    return;
                } else {
                    additions = new Array();
                    for (i=0;i<data.length;i++) {
                        if (data[i].qstype != "1") {
                            species = data[i].answers[0]['answer'];
                            scode = species.substring(0,species.search(" - ")).trim()
                            count = (data[i].answers[1]['answer'] * 1);
                            newdata = new Object();
                            newdata['name'] = species;
                            newdata['count'] = count;
                            additions.push(newdata);
                        }
                    }
                    //now, for each addition, you need to loop through the existing data structures, and see if the thing exists.  if it does, add the data; if not, add the thing, then add the data.
                    var existingdata = chart.series;
                    for (i=0;i<additions.length;i++) {
                        isnewpoint = true;
                        for (j=0;j<existingdata.length;j++) {
                            if (existingdata[j].name == additions[i].name) {
                                isnewpoint = false
                                count = additions[i].count;
                                point = [now.getTime(),count];
                                chart.series[j].addPoint(point, true, shift);
                                shift = false; //this way, only one shift occurs - the first time through adding a new point to an existing data set. this will control against future shifting, either from other datapoints having new points added, 
                            }
                        }
                        if (isnewpoint) {
                            newseries = new Object();
                            count = additions[i].count;
                            newseries['name'] = additions[i].name;
                            for (j=0;j<length;j++) {
                                newseries['data'].push(0);
                            }
                            newseries['data'].push(count);
                            chart.series.push(newseries);
                        }
                    }
                    //we have now looped through and added a new data point to all species where new data was created in this pull.  We still need to add a new point to those that were not affected.
                    existingdata = chart.series;
                    for (i=0;i<existingdata.length;i++) {
                        getname = existingdata[i].name;
                        getlength = existingdata[i].data.length;
                        if (getlength<length) { //which we established earlier as one MORE than existed previously, prior to the addition
                            point = [now.getTime(),0]
                            chart.series[i].addPoint(point, true, shift);
                        }
                    }
                }
                setTimeout(getBirds,10000);
            });
        }
    });
</script>

</html>

The problem that I'm having is pretty straightforward (but driving me nuts!), and early on in the js block. Though I'm defining the variable 'chart' as the new Highcharts chart, and I'm setting 'getBirds' as the function to load once that's loaded, the console.log line tells me that the chart is undefined, and the line below it throws an error (Uncaught TypeError: Cannot read property 'series' of undefined).

我遇到的问题非常简单(但让我发疯!),并且在 js 块的早期。虽然我将变量 'chart' 定义为新的 Highcharts 图表,并且我将 'getBirds' 设置为加载后加载的函数,但 console.log 行告诉我该图表未定义,下面的行它会引发错误 ( Uncaught TypeError: Cannot read property 'series' of undefined)。

I've checked the following:

我检查了以下内容:

  1. The Highcharts reference (http://www.highcharts.com/docs/working-with-data/preprocessing-live-data), which suggests a setup similar to mine;
  2. I've tried defining the chartvariable on its own line (which of course defines chart for my console.log, but does not define the chart.seriesrequired on the next line);
  3. I've researched stackoverflow and other docs for variable scope, but I think I'm handling it properly based on my research.
  4. I've tried reversing the order - putting the getBirds()function above the chartdefinition.
  1. Highcharts 参考 ( http://www.highcharts.com/docs/working-with-data/preprocessing-live-data),它建议了一个类似于我的设置;
  2. 我试过chart在它自己的行上定义变量(这当然为我的 console.log 定义了图表,但没有chart.series在下一行定义所需的);
  3. 我已经研究了 stackoverflow 和其他可变范围的文档,但我认为我根据我的研究正确处理了它。
  4. 我试过颠倒顺序 - 将getBirds()函数放在chart定义之上。

I'm at a loss. Any help provided is much appreciated; thanks in advance!

我不知所措。非常感谢提供的任何帮助;提前致谢!

采纳答案by dustinnewbold

The reason is likely that you cannot refer to a variable during its stages of declaration. I'm guessing that the load function is being called as it's being declared. Luckily, you can refer to the object during the function declaration. Try the following block of code.

原因可能是您无法在声明阶段引用变量。我猜是在声明 load 函数时调用了它。幸运的是,您可以在函数声明期间引用该对象。试试下面的代码块。

function getBirds(e) {
    var now = new Date(),
        et = now.getTime() / 1000, //PHP TS
        st = et - 10, //30 seconds prior in PHP
        chart = this;
    if (chart.series.length > 0) {

...declaring the chartvariable in the var block inside.

...chart在 var 块里面声明变量。

回答by Anto Jurkovi?

Trying out examples from highchart page I found out that variable chartis available only after $.json()or $ajax()call. If you try to use chartbefore that it returns undefined. Because it is and it is set only after $.json().

尝试来自 highchart 页面的示例,我发现该变量chart仅在调用$.json()$ajax()调用之后可用。如果您chart在此之前尝试使用它会返回undefined. 因为它是并且仅在 $.json() 之后设置。

Their examples with json or ajax are set this way:

他们使用 json 或 ajax 的例子是这样设置的:

var chart;

function requestData() {...}

$(document).ready(function() {
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'chart_container',
                defaultSeriesType: 'spline',
                events: {
                    load: requestData
                }
   ...
});

I did similarly with your example. From getBirds()I commented out some lines before json call:

我对你的例子做了类似的处理。从getBirds()我在 json 调用之前注释掉了一些行:

        console.log(chart);
        if (chart.series.length > 0) {
            var series = chart.series[0];
            var length = series.length + 1;
            var shift = series.data.length > 20;
        }

and moved them after json call.

并在 json 调用后移动它们。

And changed this line:

并更改了这一行:

                    //newdata['name'] = species;
                    newdata['name'] = scode;

And stop here:

停在这里:

                    for (j=0;j<length;j++) {

because of error:

因为错误:

Uncaught TypeError: Cannot call method 'push' of undefined

at line

在线

newseries['data'].push(count);

It fails because there is no array. Hope this help.

它失败,因为没有数组。希望这有帮助。

回答by ffflabs

the function declarationis interpreted before the chart object exists in the global namespace.

函数声明在全局命名空间中存在的图表对象之前被解释。

If you change the syntax to a function expressioninstead

如果你改变了语法一个函数表达式,而不是

var getBirds=function() {
    ....
};

it won't be evaluated until you call it.

在你调用它之前它不会被评估。

However, you might want to add chart as a parameter for getBirds(), it's a little cheaper than getting a variable from the global namespace.

但是,您可能希望将图表添加为 getBirds() 的参数,这比从全局命名空间获取变量要便宜一些。

EDIT

编辑

This might require a bit of debugging, but it's worth a try

这可能需要一些调试,但值得一试

    var getBirds = function(chart) {
               ...
            };
    $(document).ready(function() {
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'chart_container',
                defaultSeriesType: 'line',
                events: {
                    load: function() { 
                                     getBirds(this); 
                                     }
                }
            }
            ...
        });

        setTimeout(getBirds,10000);
    });
    }
});

回答by Vahid Taghizadeh

You should check two solution :

您应该检查两个解决方案:

  1. series variable property Shouldn't be empty array maybe its ok to enter series: null;

  2. replace your script with this code and check it again :

  1. 系列变量属性不应该是空数组也许可以输入系列:null;

  2. 用此代码替换您的脚本并再次检查:

http://notepad.cc/share/3TwgCoEano

http://notepad.cc/share/3TwgCoEano

<script type="text/javascript">
$(function() {
    $(document).ready(function() {
        var chart = new Highcharts.Chart({
            chart: {
                renderTo: 'chart_container',
                defaultSeriesType: 'line',
                events: {
                    load: getBirds
                }
            },
            title: {
                text: 'DRHW Live Data Stream'
            },
            xAxis: {
                type: 'datetime',
                tickPixelInterval: 150,
                maxZoom: 20 * 1000
            },
            yAxis: {
                title: {
                    text: 'Count Observed'
                }
            },
            series: null,
            legend: {
                layout: 'horiztonal',
                align: 'center'
            }
        });
        function getBirds() {
            var now = new Date();
            var et = now.getTime() / 1000; //PHP TS
            var st = et - 10; //30 seconds prior in PHP
            console.log(chart);
            if (chart.series.length > 0) {
                var series = chart.series[0];
                var length = series.length + 1;
                var shift = series.data.length > 20;
            }
            $.getJSON("https://path/to/json&callback=?", function(result) {
                var data = result.data;if (data.length == 0) {
                    return;
                } else {
                    additions = new Array();
                    for (i=0;i<data.length;i++) {
                        if (data[i].qstype != "1") {
                            species = data[i].answers[0]['answer'];
                            scode = species.substring(0,species.search(" - ")).trim()
                            count = (data[i].answers[1]['answer'] * 1);
                            newdata = new Object();
                            newdata['name'] = species;
                            newdata['count'] = count;
                            additions.push(newdata);
                        }
                    }
                    //now, for each addition, you need to loop through the existing data structures, and see if the thing exists.  if it does, add the data; if not, add the thing, then add the data.
                    var existingdata = chart.series;
                    for (i=0;i<additions.length;i++) {
                        isnewpoint = true;
                        for (j=0;j<existingdata.length;j++) {
                            if (existingdata[j].name == additions[i].name) {
                                isnewpoint = false
                                count = additions[i].count;
                                point = [now.getTime(),count];
                                chart.series[j].addPoint(point, true, shift);
                                shift = false; //this way, only one shift occurs - the first time through adding a new point to an existing data set. this will control against future shifting, either from other datapoints having new points added, 
                            }
                        }
                        if (isnewpoint) {
                            newseries = new Object();
                            count = additions[i].count;
                            newseries['name'] = additions[i].name;
                            for (j=0;j<length;j++) {
                                newseries['data'].push(0);
                            }
                            newseries['data'].push(count);
                            chart.series.push(newseries);
                        }
                    }
                    //we have now looped through and added a new data point to all species where new data was created in this pull.  We still need to add a new point to those that were not affected.
                    existingdata = chart.series;
                    for (i=0;i<existingdata.length;i++) {
                        getname = existingdata[i].name;
                        getlength = existingdata[i].data.length;
                        if (getlength<length) { //which we established earlier as one MORE than existed previously, prior to the addition
                            point = [now.getTime(),0]
                            chart.series[i].addPoint(point, true, shift);
                        }
                    }
                }
                setTimeout(getBirds,10000);
            });
        }
    });
});
</script>