问题描述
像这样:https://ghostbin.co/paste/ohsuar
我只需要当前的温度值。我如何获得它?
假设“weatherObject”是对象的变量。我已经尝试过“weatherObject.current.temperature”并且它输出“undefined”。
[
{
"location": {
"name": "New York,NY","lat": "40.713","long": "-74.007","timezone": "-4","alert": "","degreetype": "C","imagerelativeurl": "http://blob.weather.microsoft.com/static/weather4/en-us/"
},"current": {
"temperature": "14","skycode": "27","skytext": "Cloudy","date": "2021-05-02","observationtime": "03:00:00","observationpoint": "New York,"feelslike": "15","humidity": "40","winddisplay": "16 km/h Southwest","day": "Sunday","shortday": "Sun","windspeed": "16 km/h","imageUrl": "http://blob.weather.microsoft.com/static/weather4/en-us/law/27.gif"
},...
}
]
解决方法
您的 weatherObject 数组中有许多对象。所以你必须用你想要获取的数组元素的索引来调用它。此外,嵌套对象的键是字符串,因此您不能使用点符号来调用它。您必须使用方括号。
对于数组的第一个元素,它将是:
weatherObject[0]["current"]["temperature"]
工作示例:
var weatherObject = [
{
"current": {
"temperature": "14"
}
}
];
console.log(weatherObject[0]["current"]["temperature"]);