This article mainly introduces the differences between the forin loop of js and the foreach loop in java. The example analyzes the use skills of the forin loop of js and explains the differences between the use of the foreach loop and that of Java, it has some reference value. If you need it, you can refer to the examples in this article to analyze the differences between the js for in loop and the foreach loop in java. Share it with you for your reference. The specific analysis is as follows:
The for in loop in js is defined as follows:
The Code is as follows:
For (var variable in obj ){...}
Obj can be a common js object or an array. If obj is a js object, variable obtains the property name of the object in the traversal, rather than the value corresponding to the property. If obj is an array, variable returns the subscript of the array during traversal.
Traverse object experiment:
The Code is as follows:
Var v = {};
V. field1 = "";
V. field2 = "B ";
For (var v in v ){
Console. log (v );
}
Console output:
Field1
Field2
Traverse the array experiment:
The Code is 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 between java's foreach loop. First, the java foreach loop does not enumerate the attributes of a java object. Second, when java's foreach cyclically enumerates an array or any Object implementing the Iterable interface, for (Object o: list), Object o gets a list element, instead of the subscript in the list.
Java traversal code will not be pasted out. I often write background code, and I am familiar with foreach loops. When writing front-end js code, it is inevitable that java syntax will be applied, so the first time JavaScript's for in loop is used, it is wrong. The conclusion is clear, and no mistakes will be made in the future.
I hope this article will help you design javascript programs.