The example of this article analyzes the difference between the for in loop in js and the foreach loop in java. Share it with everyone for your reference. The specific analysis is as follows:
The for in loop in js is defined as follows:
obj can be an ordinary js object or an array. If obj is a js object, then the variable obtained during traversal is the name of the object's attribute, not the value corresponding to the attribute. If obj is an array, then the variable obtained during traversal is the subscript of the array.
Traversing objects experiment:
field1
field2
Traversing array experiment:
0
1
2
Comparing java’s foreach loop, there are two major differences. First of all, Java's 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 an element of the list, not the subscript in the list.
The Java traversal code will not be posted. I often write background code, and the foreach loop is very familiar. When writing front-end JS code, it is inevitable to apply Java syntax, so I made a mistake the first time I used the JS for in loop. If you summarize it clearly this time, you won’t make mistakes in the future.
I hope this article will be helpful to everyone’s JavaScript programming design.