【发布时间】:2018-12-19 07:55:57
【问题描述】:
我正在尝试从天气应用返回的 JSON 访问 JavaScript 中的嵌套数组。但是,如果控制台不返回cannot return property of 'x' of undefined,我似乎无法访问任何数据。我相当确定问题在于我如何与result 进行交互,但我不确定。有谁知道我如何正确访问嵌套数组中的数据?
这是我目前不工作的代码:
const weather = require('weather-js');
var val;
var temp;
var final;
weather.find({search: 'Oceanside, CA', degreeType: 'F'}, function(err, result){
if (err) console.log(err);
obj = JSON.stringify(result, null, 2);
temp = result[2].current.temperature;
console.log(temp);
final = result[1].location.name;
console.log(final)
});
这是我尝试与之交互的 JSON:
[
{
"location": {
"name": "Oceanside, CA",
"lat": "33.197",
"long": "-117.381",
"timezone": "-8",
"alert": "",
"degreetype": "F",
"imagerelativeurl": "http://blob.weather.microsoft.com/static/weather4/en-us/"
},
"current": {
"temperature": "55",
"skycode": "31",
"skytext": "Mostly Clear",
"date": "2018-12-18",
"observationtime": "22:15:00",
"observationpoint": "Oceanside, CA",
"feelslike": "55",
"humidity": "90",
"winddisplay": "3 mph Southwest",
"day": "Tuesday",
"shortday": "Tue",
"windspeed": "3 mph",
"imageUrl": "http://blob.weather.microsoft.com/static/weather4/en-us/law/31.gif"
},
"forecast": [
{
"low": "46",
"high": "64",
"skycodeday": "29",
"skytextday": "Partly Cloudy",
"date": "2018-12-17",
"day": "Monday",
"shortday": "Mon",
"precip": ""
},
{
"low": "45",
"high": "65",
"skycodeday": "34",
"skytextday": "Mostly Sunny",
"date": "2018-12-18",
"day": "Tuesday",
"shortday": "Tue",
"precip": "0"
},
{
"low": "44",
"high": "67",
"skycodeday": "34",
"skytextday": "Mostly Sunny",
"date": "2018-12-19",
"day": "Wednesday",
"shortday": "Wed",
"precip": "0"
},
{
"low": "47",
"high": "69",
"skycodeday": "30",
"skytextday": "Partly Sunny",
"date": "2018-12-20",
"day": "Thursday",
"shortday": "Thu",
"precip": "0"
},
{
"low": "47",
"high": "65",
"skycodeday": "34",
"skytextday": "Mostly Sunny",
"date": "2018-12-21",
"day": "Friday",
"shortday": "Fri",
"precip": "0"
}
]
}
]
这个问题不是 Access / process(嵌套)对象、数组或 JSON 的副本,因为据我所知,该页面上的答案涉及多个元素的数组,而这个问题没有。
【问题讨论】:
-
cannot return property of 'x' of undefined您的问题中的代码中没有x,但该错误出现在哪一行? (这听起来像是释义错误,而不是实际错误 - 请发布实际错误) -
它实际上并没有说“x”。如果我们要具体,它会显示当前或位置。 X 只是为了简单。
-
result中有一个 single 元素数组。这就是您在result[2].*上收到错误的原因 -
你的结果数组只有一个元素。这是一个对象,您正在尝试访问索引处不是零的元素。
-
这个问题与 JSON 本身无关。除了未使用的(!)
obj,任何地方都没有 JSON。
标签: javascript arrays json multidimensional-array