我正在进行一个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(不用担心会在这之后改变)
'if(i.dt = timeNow)'和整数的其他属性??? – Teemu
对不起,我不清楚你在问什么。你能否更具体一些? @Teemu – thatemployee
我应该怎么具体?我指出,你正试图读取一些整数的属性,显然没有定义......作为奖励,你可以看到,你正在使用赋值运算符而不是条件中的相等运算符。 – Teemu