2017-07-15 76 views
0

請幫助....嘗試執行下文提到的功能,但Web控制檯始終顯示獲取JavaScript的未定義類型錯誤

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

我能夠在警報打印的值,但代碼是不給輸出到瀏覽器因爲這個錯誤。嘗試在不同的位置初始化j和使用不同的增量methods.How可以i獲得通過這個類型錯誤

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(); 
    }; 
+2

在上一次迭代中,不能有下一個「預測」。你想用這個做什麼? – PeterMader

+0

我解析從json傳遞的xml數據。 – AKB

+0

非常好,但最後一個元素之後的元素應該是什麼?當然沒有定義。 – PeterMader

回答

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

謝謝Alberto.It工作:) – AKB

相關問題