如何在Javascript中遍历数组元素

时间:2016-05-13 09:07:17

标签: javascript arrays

如何在javascript中遍历数组的每个元素。

<script>
            var arrayCollection;
            $(function() {
                arrayCollection = [
                    {"id": "animal", "parent": "#", "text": "Animals"},
                    {"id": "device", "parent": "#", "text": "Devices"},
                    {"id": "dog", "parent": "animal", "text": "Dogs"},
                    {"id": "lion", "parent": "animal", "text": "Lions"},
                    {"id": "mobile", "parent": "device", "text": "Mobile Phones"},
                    {"id": "lappy", "parent": "device", "text": "Laptops"},
                    {"id": "daburman", "parent": "dog", "text": "Dabur Man", "icon": "/"},
                    {"id": "CN=dalmatian", "parent": "dog", "text": "Dalmatian", "icon": "/"},
                    {"id": "african", "parent": "lion", "text": "African Lion", "icon": "/"},
                    {"id": "indian", "parent": "lion", "text": "Indian Lion", "icon": "/"},
                    {"id": "apple", "parent": "mobile", "text": "Apple IPhone 6", "icon": "/"},
                    {"id": "samsung", "parent": "mobile", "text": "Samsung Note II", "icon": "/"},
                    {"id": "lenevo", "parent": "lappy", "text": "Lenevo", "icon": "/"},
                    {"id": "hp", "parent": "lappy", "text": "HP", "icon": "/"}
                ];}</script>

我曾尝试过使用for循环的takin gthe长度和访问循环中的元素

arrayCollection[iterator]

但它只返回[Object,Object] 也尝试过类型转换,但不起作用。

2 个答案:

答案 0 :(得分:2)

您可以使用forEach()方法执行此操作:

arrayCollection.forEach(function(v,i){
                          console.log(v.id)
                        })

其中i = index和v = value,因为该值是一个对象,您可以直接访问它的属性。

答案 1 :(得分:-1)

这是有效的,我测试过,

for (i in arrayCollection) {
       item = arrayCollection[i];
       console.log("id=" + item['id'] + ", parent="+item["parent"] + ", text=" + item['text']);
 }

输出:

 id=animal, parent=#, text=Animals
 ....

对于那些不想使用“for..in”的人,您也可以使用索引,例如:

for (i=0;i<arrayCollection.length; i++) {
    item = arrayCollection[i];
    console.log("id=" + item['id'] + ", parent="+item["parent"] + ", text=" + item['text']);
}