Differences between the js for in loop and the foreach loop in java, jsforeach

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.