gpt4 book ai didi

javascript - API 响应返回未定义

转载 作者:行者123 更新时间:2023-11-28 17:47:58 25 4
gpt4 key购买 nike

我正在进行一个 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 (不用担心此后会发生变化)

Codepen

最佳答案

您的代码中存在一些问题

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

Forked pen 。为了更好的输出,一些日志被注释掉。

关于javascript - API 响应返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46283962/

25 4 0
文章推荐: javascript - 如何将参数传递给 onclick 函数
文章推荐: javascript - 如何在鼠标悬停时停止滚动
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com