类型错误:无法读取两个 getJSON 函数之间的值属性



当我的 2 个 json 数组的长度相同时,我不会收到错误。但是当他们不是时,我会得到一个TypeError: Connot read property of undefined.

杰森:

json1:

[
{
"date": "2019-07-05",
"x": 1246567,
"y": 598045
},
{
"date": "2019-07-06",
"x": 1021607,
"y": 452854
},
{
"date": "2019-07-07",
"x": 1031607,
"y": 467854
}
]

JSON2:

[
{
"date": "2019-07-05",
"v": 3132769,
"pv": 6643094
},
{
"date": "2019-07-06",
"v": 2643611,
"pv": 6059584
}
]

JavaScript

$.getJSON(json1, result => {
result.forEach((elem, i, array) => {
$('#x').text(elem.x);                            
$('#y').text(elem.y);
});
$.getJSON(json2, result => {
result.forEach((elem, i, array) => {
let yo = 0;
if ((elem.date.indexOf(json[i].date) !== -1)) {
yo = json[i].x/elem.v)
$('#v').text(elem.v);                            
$('#pv').text(elem.pv);
$('#vpv').text(yo);  
} 
});
});

当数组的长度相互匹配时,一切正常。但是当一个比另一个长时,我得到

TypeError: Cannot read property x of undefined (at json[i].x). 

我什至添加了条件

if ((elem.date.indexOf(json[i].date) !== -1)). 

我以为这会解决这个问题。但我仍然收到错误。我该如何解决这个问题?

你需要处理异步调用,你把它们当作异步调用来处理。由于您使用的是jQuery,因此可以使用when()

$.when(
$.getJSON(url1),
$.getJSON(url2)
).done(function(data1, data2) {
console.log(data1[0]);
console.log(data2[0]);
});

现在你的逻辑在找到匹配项方面存在缺陷。就个人而言,我会在处理数据之前将它们结合起来

const data1 = [{
"date": "2019-07-05",
"x": 1246567,
"y": 598045
},
{
"date": "2019-07-06",
"x": 1021607,
"y": 452854
},
{
"date": "2019-07-07",
"x": 1031607,
"y": 467854
}
]
const data2 = [{
"date": "2019-07-05",
"v": 3132769,
"pv": 6643094
},
{
"date": "2019-07-06",
"v": 2643611,
"pv": 6059584
}
]
const dataPoints = data1.reduce((obj, item) => {
obj[item.date] = item
return obj
}, {})
data2.forEach(item => {
//dataPoints[item.date] = dataPoints[item.date] || {}
//Object.assign(dataPoints[item.date], item)
dataPoints[item.date] = { ...(dataPoints[item.date] || {}),
...item
}
})
Object.values(dataPoints).forEach(item => {
console.group(item.date)
if (item.x !== undefined && item.v !== undefined) {
console.log(item.x / item.v);
} else {
console.log("can't do calc")
}
console.groupEnd(item.date)
})

最新更新