Differences between the js for in loop and the foreach loop in java, jsforeach
This article analyzes 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:
Copy codeThe 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:
Copy codeCode: var v = {};
V. field1 = "";
V. field2 = "B ";
For (var v in v ){
Console. log (v );
}
Console output:
Field1
Field2
Traverse the array experiment:
Copy codeThe 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.