我觉得真正阻碍我能力的事情之一是理解如何有效地使用数组和对象。我掌握了基础知识,但是当涉及到复杂对象中需要特定的键和值时,我会迷失方向。因此,在这个示例中,我从 openweathermap 获取一个对象。该对象看起来像这样:
{
"coord":{
"lon":-83.15,
"lat":41.51
},
"weather":[
{
"id":721,
"main":"Haze",
"description":"haze",
"icon":"50d"
}
],
"base":"cmc stations",
"main":{
"temp":287.05,
"pressure":1024,
"humidity":47,
"temp_min":286.15,
"temp_max":288.15
},
"wind":{
"speed":5.1,
"deg":50,
"gust":9.3
},
"clouds":{
"all":40
},
"dt":1443728852,
"sys":{
"type":1,
"id":1435,
"message":0.0115,
"country":"US",
"sunrise":1443699000,
"sunset":1443741203
},
"id":5165215,
"name":"Oak Harbor",
"cod":200
}
我了解如何使用 each() 迭代数组
$.getJSON( "http://api.openweathermap.org/data/2.5/weather?zip=43452,us&APPID=6c62bbbc17614bb4c0cae3095e0b5a89", function(obj) {
$.each(obj.main, function(key, val) {
//do something//
});
});
但是,如果我想访问对象中更深层的内容,例如我特别想要温度值,然后将其分配给全局变量以在脚本外部使用,该怎么办?我认为不需要特定的解决方案,但更多的是关于如何使用像这样的有点复杂的对象的良好可靠的解释。
感谢您的帮助!
所以我现在有了这个,但该值没有从函数中传递出去?
$.getJSON( "http://api.openweathermap.org/data/2.5/weather?zip=43452,us&APPID=6c62bbbc17614bb4c0cae3095e0b5a89", function(obj) {
currentTemp = (obj.main.temp * 9/5 - 459.67);
alert(currentTemp);
});
alert(currentTemp);
最佳答案
$.getJSON( "http://api.openweathermap.org/data/2.5/weather?zip=43452,us&APPID=6c62bbbc17614bb4c0cae3095e0b5a89", function(obj) {
$.each(obj.main, function(key, val) {
if(val.temp)
{
// do what you want with the temperature
}
});
});
关于javascript - JS/JQuery 获取多维对象中键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32897377/