如何在Javascript中遍历数组的元素
How to traverse through elements of array in Javascript
如何在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循环,方法是获取长度并将循环中的元素作为访问
arrayCollection[iterator]
但它只返回[Object,Object]也尝试过按类型转换,但不起作用。
您可以使用forEach()
方法来实现这一点,如下所示:
arrayCollection.forEach(function(v,i){
console.log(v.id)
})
其中i=索引,v=值,因为值是一个对象,所以可以直接访问它的属性。
我测试了
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']);
}
相关文章:
- 在函数中添加数组元素的数值
- 访问JSON对象内部的数组元素
- Mongoose-在更新中删除数组元素
- javascript数组元素是否知道其封闭数组
- 将数组元素附加到FormData dos'不适用于Firefox 15
- 如何在javascript中使用click函数选择数组元素
- 如何在JavaScript中剥离数组元素中的非整数
- 消隐数组元素是否生成自己的属性
- 如何使一个Math.random数组元素比另一个数组元素更有可能被选中
- 在Codrops的内容中添加数组元素展开缩略图网格预览
- 如何使用Jquery水平打印表中的数组元素,并在某个元素之后垂直打印
- 如何访问数组中的数组元素(JavaScript)
- 生成ACF标记位置的数组(元素列表后缺少])
- validate.js验证数组元素
- JavaScript Unshift EACH 数组元素
- 如何在加号运算符之后选择数组元素的一部分
- 访问标记图标的图像数组元素
- JavaScript 合并相同的数组元素
- 删除仅空格数组元素
- JavaScript闭包和返回数组元素