繁体   English   中英

Java for循环无法在另一个for循环中获取长度

[英]Javascript for loop not getting length inside another for loop

我正在尝试遍历从服务器获取的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是什么类型时,我将其视为对象。 我的问题是我的代码有什么问题。

您的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); } } } 

您的列表包含许多不具有below_min属性的元素,当您要访问该属性时,它将返回undefined

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM