如果 json 值存在,Google Maps API V3 地理编码 javascript
我对 Javascript 有点陌生,我正在尝试创建一个非常简单的 if 语句。
我正在向 google geocoder 发送地址并接收 json 结果。我正在解析结果并打印到我的 html 文档中。
我现在只想尝试打印实际存在的值,以免使我的代码崩溃。
现在我有:
document.getElementById('lat').innerHTML = [results[1].geometry.location.lat()];
并且它有效,但如果 json 结果中不存在“results[1].geometry.location.lat()”,我不希望该行运行。
我已经尝试过:
if ([results[1].geometry.location.lat()] != null) {
document.getElementById('lat').innerHTML = [results[1].geometry.location.lat()];
}
但即使那里没有价值,该线路仍然运行。我一定做错了。请帮助某人。
因为每次值都会不同,所以我只想在有任何值时运行该行。
I am somewhat a novice with Javascript and I am trying to create a very simple if statement.
I am sending an address to the google geocoder and receiving the json result. I'm parsing the result and printing into my html document.
I now only want to attempt to print values that actually exist to keep from crashing my code.
right now I have:
document.getElementById('lat').innerHTML = [results[1].geometry.location.lat()];
and it works, but I don't want that line to run if "results[1].geometry.location.lat()" doesn't exist in the json result.
I have tried:
if ([results[1].geometry.location.lat()] != null) {
document.getElementById('lat').innerHTML = [results[1].geometry.location.lat()];
}
but the line still runs even if there is no value there. I gotta be doing this wrong. Please help someone.
Because the value will be different every time, I just want the line to run if there is ANY value.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
[results[1].geometry.location.lat()]
是数组的简写;它永远不会为空。取出
[]
。真正安全的测试方法是:
[results[1].geometry.location.lat()]
is shorthand for an array; it will never be null.Take out the
[]
.The truly safe way to test would be:
如果您知道几何体存在,但不确定位置是否存在,则可以检查未定义。
如果您甚至不知道几何是否存在,那么您还需要检查它是否未定义。
If you know that geometry exists but you are unsure if location exists or not, you can check against undefined.
If you don't know if even geomery exists, then you would also need to check if that is undefined.