Home  >  Article  >  Web Front-end  >  Analysis of the difference between the for in loop in js and the foreach loop in java

Analysis of the difference between the for in loop in js and the foreach loop in java

高洛峰
高洛峰Original
2017-01-21 15:52:331606browse

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:

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 attribute during traversal, not the value corresponding to the attribute. If obj is an array, then the variable obtained during traversal is the subscript of the array.

Traverse the object experiment:

var v = {};  
v.field1 = "a";  
v.field2 = "b";  
for(var v in v) {  
    console.log(v);  
}

Output under the console:


##field1

field2

Traverse the array Experiment:

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

Use java’s foreach loop to do it In comparison, 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.

For more related articles on the difference analysis between the for in loop in js and the foreach loop in java, please pay attention to the PHP Chinese website!

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