Home >Web Front-end >JS Tutorial >Analysis of the difference between the for in loop in js and the foreach loop in java_javascript skills

Analysis of the difference between the for in loop in js and the foreach loop in java_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:17:261340browse

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:

Copy code The code is 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 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:

Copy code The code 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

Traversing array experiment:

Copy code 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

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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn