AKB
AKB

Reputation: 33

Getting javascript undefined TypeError

Please help....Tried executing the below mentioned function but web console always shows

TypeError: xml.location.forecast[j] is undefined

I was able to print the values in alert but the code is not giving output to the browser because of this error. Tried initializing j in different locations and used different increment methods.How can i get pass this 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();
  };

Upvotes: 0

Views: 66

Answers (1)

Alberto Trindade Tavares
Alberto Trindade Tavares

Reputation: 10356

You are trying to access the element after the last one. You can check if there is the element pointed by j before proceeding:

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;
    });
};

Upvotes: 1

Related Questions