我正在進行一個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