0

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();
  };
4
  • 2
    In the last iteration, there can't be a next forecast. What do you want to achieve with that? Commented Jul 15, 2017 at 9:40
  • I am parsing xml data delivered from a json. Commented Jul 15, 2017 at 9:42
  • Very well, but what should the element after the last element be? It's not defined, of course. Commented Jul 15, 2017 at 9:42
  • Can u please make changes on code and put as a comment Peter.I have trimmed the code just to show the main stuffs. Commented Jul 15, 2017 at 9:45

1 Answer 1

1

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;
    });
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.