【问题标题】:Getting javascript undefined TypeError获取javascript未定义的TypeError
【发布时间】:2017-12-20 08:47:34
【问题描述】:

请帮忙....尝试执行下面提到的功能,但网页控制台总是显示

TypeError: xml.location.forecast[j] 未定义

我能够打印警报中的值,但由于此错误,代码没有向浏览器提供输出。尝试在不同位置初始化j 并使用不同的增量方法。i 如何通过此 TypeError

Meteogram.prototype.parseYrData = function () {

var meteogram = this,xml = this.xml,pointStart;

if (!xml) {
    return this.error();
}

var j;

$.each(xml.location.forecast, function (i,forecast) {

j= Number(i)+1;

var oldto = xml.location.forecast[j]["@attributes"].iso8601;
var mettemp=parseInt(xml.location.forecast[i]["@attributes"].temperature, 10);

var from = xml.location.forecast[i]["@attributes"].iso8601;
var to = xml.location.forecast[j]["@attributes"].iso8601;

    from = from.replace(/-/g, '/').replace('T', ' ');
    from = Date.parse(from);
    to = to.replace(/-/g, '/').replace('T', ' ');
    to = Date.parse(to);

    if (to > pointStart + 4 * 24 * 36e5) {
        return;
    }
    if (i === 0) {
        meteogram.resolution = to - from;
    }


    meteogram.temperatures.push({
        x: from,
        y: mettemp,
        to: to,
        index: i
    });

if (i === 0) {
        pointStart = (from + to) / 2;
    }
});
this.smoothLine(this.temperatures);
this.createChart();
  };

【问题讨论】:

  • 在上一次迭代中,不能有下一个forecast。你想用它实现什么?
  • 我正在解析从 json 传递的 xml 数据。
  • 很好,但是最后一个元素之后的元素应该是什么呢?当然,它没有定义。
  • 您能否对代码进行更改并作为评论彼得。我已经修剪了代码只是为了显示主要内容。

标签: javascript jquery highcharts undefined typeerror


【解决方案1】:

您正在尝试访问最后一个元素之后的元素。您可以在继续之前检查是否有j指向的元素:

Meteogram.prototype.parseYrData = function () {
    var meteogram = this,
        xml = this.xml,
        pointStart;

    if (!xml) {
        return this.error();
    }

    var i = 0;
    var j;

    $.each(xml.location.forecast, function (i, forecast) {
        j = Number(i) + 1;
        if (!xml.location.forecast[j]) return;

        var from = xml.location.forecast[i]["@attributes"].iso8601;
        var to = xml.location.forecast[j]["@attributes"].iso8601;
    });
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-12
    • 2017-06-29
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 2017-01-24
    • 1970-01-01
    相关资源
    最近更新 更多