2017-09-18 207 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