2017-09-18 148 views
0

我正在进行一个API调用,该调用返回包含一堆对象的Array的JSON响应。每个物体都有一个关键字“dt”,它是一天中特定时间的时间戳,另一个关键字“高度”是海洋预测的或当时的潮汐高度。API响应返回undefined

我只想要在任何时候发生AJAX呼叫的时间点的当前潮位高度。这是我为了实现创建函数:

let tideApi = 'https://www.worldtides.info/api?heights&lat=45.202&lon=-123.963&key=24e4ff14-6edf-4f79-9591-e47f9e0e21e1'; 

$.getJSON(tideApi, function(response) { 

    // Create Global variable 
    let tideHeight = 0; 
    // get current time 
    let nowMil = new Date().getTime(); 
    // round that time to the nearest halfhour and convert back to timestamp (JSON timestamps are set in intervals of 30 minutes) 
    let timeNow = Math.round(nowMil/1000/60/30) * 30 * 60 * 1000; 

    // set entire array to variable 
    let heightArray = response.heights; 
    // get length 
    len = heightArray.length 
    // loop through each object in height array 
    for (var i=0; i < len; i++) { 
    // if one of the objects timestamp equals current time 
    if (i.dt = timeNow) { 
     // set tide height to variable 
     tideHeight = i.height; 
     // return tide height (curretly returning undefined) 
     console.log("Tide Height: " + tideHeight); 
     return tideHeight; 
    } else { 
     console.log("Error, no time found"); 
    } 
    } 
    // put tide height into div 
    $("#tideStat").append("<p>" + tideHeight + "</p>"); 

}); 

它目前返回undefined是有原因的,我在努力搞清楚。任何帮助将是伟大的!

API Call(不用担心会在这之后改变)

Codepen

+1

'if(i.dt = timeNow)'和整数的其他属性??? – Teemu

+0

对不起,我不清楚你在问什么。你能否更具体一些? @Teemu – thatemployee

+0

我应该怎么具体?我指出,你正试图读取一些整数的属性,显然没有定义......作为奖励,你可以看到,你正在使用赋值运算符而不是条件中的相等运算符。 – Teemu

回答

2

代码中有几个问题

  1. let timeNow = Math.round(nowMil/1000/60/30) * 30 * 60 * 1000;。你的API似乎没有返回毫秒。删除* 1000
  2. 您无法访问您的heightArray中的项目。相反,只需检查dtheight财产i,这是一个整数。因此分别将i.dti.height改为heightArray[i].dtheightArray[i].height
  3. 当您使用if (lhs = rhs)时,您试图分配,而不是比较。因此,在if条件下将=更改为===
  4. 删除return tideHeight;。我想你想要break?但不知道。由于这一行,您最后的jQuery相关代码不会执行。

Forked pen。一些日志注释了更好的输出。

+1

你太棒了,非常感谢。另外感谢你教育我为什么我的代码错了,我犯的错误,所以我没有再做。即使它有明显的答案,也不存在这样愚蠢的问题。每个人都必须从某个地方开始。在任何人不鼓励提问的环境中,我都不是一个很大的粉丝,而且最近似乎也是如此。信仰在社区中得到恢复。 – thatemployee

1

使用括号符号引用i对象heightArray阵列,===操作的,而不是=,这是赋值运算符

if (heightArray[i].dt === timeNow) { 
    // do stuff 
    tideHeight = heightArray[i].height; 
} 
+0

谢谢。这绝对是一个巨大的帮助。我现在正在碰到错误catch语句,所以我会对此进行一些故障排除。你确实回答了我为什么回到undefined的问题,所以我会接受你作为答案。 – thatemployee

+0

'return tideHeight'的预期结果是什么? – guest271314

+0

具有与当前时间相同的dt时间戳的对象的height属性。 – thatemployee