简体   繁体   English

如何遍历JavaScript对象中的数组?

[英]How to loop over an array within a JavaScript object?

Very new to JavaScript objects, so I am not to sure how to go about doing this. 对JavaScript对象来说是非常新的东西,所以我不确定该怎么做。

Within my object, I have an array called myArray . 在我的对象中,我有一个名为myArray的数组。 I am attempting to loop over it to print out everything on the page. 我试图遍历它以打印出页面上的所有内容。 Usually there is aa lot more data within the object, but it has been removed for this example. 通常,对象中有很多数据,但是在本示例中已将其删除。

This is my object: 这是我的对象:

var data = [
    {
        myArray:
        {
            name: 'name1',
            code: 'code1',
            data: {
                date: '20-Apr-2014',
                signal: 'signal1'
            }
        },
        {
            name: 'name2',
            code: 'code2',
            data: {
                date: '21-Apr-2014',
                signal: 'signal2'
            }
        }
    }
]

This is my iteration code: 这是我的迭代代码:

var arrayLength = data.myArray.length - 1;
for (var i = 0; i <= arrayLength; i++) {
    var name = data.myArray[i].name;
    console.log(name);
}

My code above should produce the results in the console name1 and name2 . 我上面的代码应在控制台name1name2产生结果。 However, I am getting an error of Cannot read property 'length' of undefined . 但是,我收到一个Cannot read property 'length' of undefined的错误。

How can I change my above code to do this? 如何更改上面的代码来做到这一点?

Your object should use brackets for the array: 您的对象应在数组中使用方括号:

var data = {
    myArray: [
    {
        name: 'name1',
        code: 'code1',
        data: {
            date: '20-Apr-2014',
            signal: 'signal1'
        }
    },
    {
        name: 'name2',
        code: 'code2',
        data: {
            date: '21-Apr-2014',
            signal: 'signal2'
        }
    }
    ]
}

I've also removed the outermost brackets, since it would appear from your question that your intent was to have a single array inside an object, and not an array of arrays. 我也删除了最外层的括号,因为从您的问题中可以看出,您的意图是在对象内只有一个数组,而不是数组。

With the object above, your iteration code will work fine. 使用上面的对象,您的迭代代码将正常工作。

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

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