This article analyzes the difference between the for in loop of js and the foreach loop in java. Share it for your reference. The specific analysis is as follows:
The for in loop in js is defined as follows:
Copy the code as follows: for(var variable in obj) { ... }
obj can be a normal js object or an array. If obj is a js object, then variable gets the name of the object's attribute in the traversal, not the value corresponding to the attribute. If obj is an array, then variable gets the subscript of the array in the traversal.
Traversing object experiments:
The code copy is as follows: var v = {};
v.field1 = "a";
v.field2 = "b";
for(var v in v) {
console.log(v);
}
Output under the console:
field1
field2
traversal array experiment:
Copy the code as follows: var mycars = new Array()
mycars[0] = "Saab"
mycars[1] = "Volvo"
mycars[2] = "BMW"
for (var x in mycars){
console.log(x);
}
Console output:
0
1
2
There are two major differences when comparing Java's foreach loop. First of all, the java foreach loop will not enumerate the properties of a java object. Secondly, when Java's foreach loop enumerates an array or any object that implements the Iterable interface, for(Object o : list), object o gets a list element, not a subscript in the list.
The java traversal code will not be posted. I often write background code and it is very familiar with foreach loops. When writing front-end js code, it is inevitable to apply Java syntax, so I made a mistake when using js for in loop for loop for the first time. This time I have made a clear summary and I will not make any mistakes in the future.
I hope this article will be helpful to everyone's JavaScript programming.