【发布时间】:2017-09-18 16:16:47
【问题描述】:
我正在做一个 API 调用,它返回一个带有一堆对象的数组的 JSON 响应。每个对象都有一个键“dt”,它是一天中特定时间的时间戳,另一个键是“height”,它是当时海洋的预测或过去潮汐高度。
我只想要 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>");
});
由于我正在努力弄清楚的原因,它目前返回未定义。任何帮助都会很棒!
API Call(以后不用担心会变)
【问题讨论】:
-
if (i.dt = timeNow)和整数的其他属性??? -
很抱歉,我不清楚您在问什么。你能更具体一点吗? @Teemu
-
我应该做到多具体?我指出,您正在尝试读取整数的某些属性,这些属性显然没有定义……作为奖励,您可以看到,您在条件中使用的是赋值运算符而不是相等运算符。
-
足够具体,我不必问你更清楚什么'???'方法。我只是想更好地了解如何改进我的逻辑。我们都只是想了解我的朋友。我不确定为什么没有定义整数。这有明确的原因吗? @Teemu
-
已定义,但它是您在上面一行声明的数字,并将
0设置为它。数字显然没有在 AJAX 响应中定义的任何属性。
标签: javascript jquery arrays json ajax