Two kinds of for loops in js:
for (var i in obj) and for (var i=0; i<obj.length; i++)
Difference:
for (var i in obj) is an enhanced for loop, a traversal method that does not use subscripts, simple and efficient, but the disadvantage is that subscripts cannot be used.
If you want to loop through a json object, use the first one
If you want to loop through an array object use the second
for(var i in obj)
1. When traversing the array, i is the index value, and arr[i] is the value corresponding to the index number.
2. When traversing the string, i is the index value, and arr[i] is the character corresponding to the index number.
3. When traversing the json object, i is the value before the colon, and json[i] is the value after the colon.
Traversing nested arrays (recursion) [judgment subset]
traversal(dataInfo)//dataInfo是要循环遍历的集合
//遍历方法
function traverse(data) {
for (var i in data) {
if (data[i].children) {
traverse(data[i].children)
}
if (!data[i].children.length) {
delete data[i].children;
}
}
}
For example my collection is as follows
I want to get the Name and output it, the code is as follows
traversal(dataInfo)//dataInfo是要循环遍历的集合
//遍历方法
function traverse(data) {
for (var i in data) {
alert(data[i].Name)
if (data[i].children) {
traverse(data[i].children)
}
if (!data[i].children.length) {
delete data[i].children;
}
}
}