![](/img/trans.png)
[英]api response returned in javascript returning undefined unless i do &&
[英]API response is returning undefined
我正在进行API调用,以返回带有一堆对象的Array的JSON响应。 每个对象都有一个键“ dt”,它是一天中特定时间的时间戳,另一个键是“高度”,它是海洋在该时刻的预计或过去的潮汐高度。
我只希望当前潮汐的高度在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调用 (此后不必担心会更改)
您的代码中有一些问题
let timeNow = Math.round(nowMil/1000/60/30) * 30 * 60 * 1000;
。 您的API似乎没有返回毫秒。 删除* 1000
。 heightArray
访问项目。 而是只检查i
dt
和height
属性,它是一个整数。 因此,将i.dt
和i.height
更改为heightArray[i].dt
和heightArray[i].height
。 if (lhs = rhs)
,您尝试分配而不是进行比较 。 因此,在if
条件下将=
更改为===
。 return tideHeight;
。 我想你想break
吗? 虽然不确定。 由于这一行,您最后的jQuery
相关代码无法执行。 分叉的笔 。 一些日志被注释掉以获得更好的输出。
使用括号符号引用heightArray
数组的i
对象, ===
运算符,而不是=
,它是赋值运算符
if (heightArray[i].dt === timeNow) {
// do stuff
tideHeight = heightArray[i].height;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.