In this paper, we analyze the difference between JS's for In loop and the Foreach loop in Java. Share to everyone for your reference. The specific analysis is as follows:
The For In loop in JS is defined as follows:
Copy Code code as follows:
for (var variable in obj) {...}
Obj can be an ordinary JS object or an array. If obj is a JS object, then the variable gets the name of the object's property, not the value of the attribute, in the traversal. If obj is an array, then the variable in the traversal is the subscript of the array.
Traversal Object Experiment:
Copy Code code as follows:
var v = {};
V.field1 = "a";
V.field2 = "B";
For (Var v. in V) {
Console.log (v);
}
Output under console:
Field1
Field2
Traversal Array Experiment:
Copy Code 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 big differences in comparing Java's foreach loops. First, the Java foreach Loop does not enumerate the properties of a Java object. Second, the Java foreach Loop enumerates an array or any object that implements the Iterable interface, for (object o:list), object o gets the list element, not the subscript in the list.
The Java traversal code is not posted. Often write background code, the Foreach loop is very familiar. Writing the front desk JS code, it is inevitable to apply the Java syntax, so the first time with JS for in the loop when the mistake. The summary is clear and there will be no mistakes in the future.
I hope this article will help you with your JavaScript programming.