我试图遍历从服务器获取的json值,如下所示:
[
{
below_min: [
{
y: 0,
label: "Bhagalpur",
color: "Red"
},
{
y: 0,
label: "Gopalganj",
color: "Red"
}
]
},
{
min: [
{
y: 0.2,
label: "Samastipur",
color: "Orange"
},
{
y: 0.3,
label: "Saran",
color: "Orange"
}
}
]
}
]
我正在使用此循环代码来获取我的below_min数组的值:
for (let index = 0; index < res.length; index++) {
const element = res[index];
console.log(element.below_min);
// const u = element.below_min
for (let index = 0; index < element.below_min.length; index++) {
const h = element.below_min[index];
}
}
但我遇到错误:
ERROR TypeError: Cannot read property 'length' of undefined
我已经尝试了一些事情,例如当我试图查看below_min是什么类型时,我将其视为对象。我的问题是我的代码有什么问题。
答案 0 :(得分:0)
您的Javascript对象文字存在语法问题。所以我试图纠正它。
您可以尝试以下代码,并获得正确获取below_min
的想法:
const res = [
{
below_min: [
{
y: 0,
label: "Bhagalpur",
color: "Red"
},
{
y: 0,
label: "Gopalganj",
color: "Red"
}
]
},
{
min: [
{
y: 0.2,
label: "Samastipur",
color: "Orange"
},
{
y: 0.3,
label: "Saran",
color: "Orange"
}
]
}
];
for (let index = 0; index < res.length; index++) {
const element = res[index];
if(element.below_min){
for (let minIndex = 0; minIndex < element.below_min.length; minIndex++) {
const h = element.below_min[minIndex];
console.log(h);
}
}
}
答案 1 :(得分:0)
您的列表包含许多不具有below_min
属性的元素,当您要访问该属性时,它将返回undefined
。