我正在开发一个气象应用程序,它可以提取一些数据。
中途,它停止将其中一个对象识别为对象,并抛出:Uncaught (in promise) TypeError: data is undefined
现在,这似乎与我的嵌套if有关。如果我删除指示的行,它运行良好,promise完成。否则会抛出错误。
这是停止工作的脚本。
async function processHourly(hourly){
let data = await pullData(hourly); // Pull data is just fetch.then(return res.json)
data = data.properties;
let dataHours = data.periods; // Exception thrown on data, here.
let weatherObj = new Array;
let objNum=0;
let avgTemp;
let dateCheck;
for(x in dataHours)
{
// Grab the day's hours
//console.log(dataHours[x].startTime)
if(dataHours[x].startTime.slice(8,10)!=dateCheck){
weatherObj[objNum] = new Weather
weatherObj[objNum].Year = dataHours[x].startTime.slice(0,4) // takes 0-3
weatherObj[objNum].Month = dataHours[x].startTime.slice(5,7)-1 // takes 5 and 6
weatherObj[objNum].Date = dataHours[x].startTime.slice(8,10) // takes 8 and 9
weatherObj[objNum].getDay();
objNum++;
typeof(weatherObj[objNum]) // If these are removed
if(dataHours[x].startTime.slice(11,13)>=12) // Then it processes data as
{ // a completed promise.
weatherObj[objNum].IsNight = true; //
} //
}
dateCheck=dataHours[x].startTime.slice(8,10);
}
console.log(dataHours)
for(x in weatherObj){
weatherObj[x].setDateObj()
console.log(x,weatherObj[x].dateObj)
}
}
有人知道为什么吗?我觉得我错过了一些很简单的事情。变量似乎不会影响数据的范围?
编辑-1/7/22,澄清pullData功能
项目
这是一个简单的天气应用程序,将在屏幕上为社区循环播放。它从weather.gov api的小时预报中提取数据,并处理一些数据。这就是正在执行的过程。
数据的json方案可以在这里找到
虽然我不完全确定原因,但似乎使用=来分配值会导致问题,而不是使用数组函数。
以下是对原文的缩写,强调了我的问题所在。
损坏的代码
if(dataHours[x].startTime.slice(8,10)!=dateCheck){
weatherObj[objNum] = new Weather /** THIS IS OUR PROBLEM CHILD **/
...
...
if(dataHours[x].startTime.slice(11,13)>=12) // Then it processes data as
{ // a completed promise.
weatherObj[objNum].IsNight = true; //
} //
}
更正
相反,我使用.push((将新的天气对象分配给该点。接下来,在当前天气对象迭代创建时,将objNum指定为等于该对象的索引。
我还添加了预测时间的关键字,以便稍后处理和求平均值。
我最后得到的更正如下。
工作代码
let checkable; //Good for testing
async function processHourly(hourly)
{
let data = await pullData(hourly);
data = data.properties;
let dataHours = data.periods;
let weatherObj = new Array;
let objNum=0;
let dateCheck=-1; // forces first pass to always create a new weather
console.log(dataHours[0]) // To double check variable names
for(x in dataHours){ // Start creating objects
if( dataHours[x].startTime.slice(8,10)!=dateCheck){
weatherObj.push(new Weather);
dateCheck = dataHours[x].startTime.slice(8,10);
objNum = weatherObj.length-1
}
weatherObj[objNum].hourTemp.push({
hour : dataHours[x].startTime.slice(11,13),
temp : dataHours[x].temperature
});
weatherObj[objNum].hourForecast.push({
hour : dataHours[x].startTime.slice(11,13),
forecast : dataHours[x].shortForecast
})
weatherObj[objNum].hourWindDir.push({
hour : dataHours[x].startTime.slice(11,13),
direction : dataHours[x].windDirection
})
weatherObj[objNum].hourWindspeed.push({
hour : dataHours[x].startTime.slice(11,13),
speed : dataHours[x].windSpeed.slice(0,-4)
})
}
checkable = weatherObj
}