JS Foreach,for in, for of

Source: Internet
Author: User

foreach Traversal array

[].foreach (function (value, index, array) {//...});

Example

var myarry =[1,2,3,4= ' four '; Myarry.foreach ((value,index,arr)={  Console.log (value); }); // 1 // 2 // 3 // 4
foreach iterates through an array instead of traversing the object oh, and cannot be terminated during traversal, it must be traversed once for each value to stop

Note that it is similar to the $.each of jquery, except that the arguments are exactly the Opposite.

$.each ([], function (index, value, array) {//...});

$.each iterating over an array or an array of classes

The 1th and 2nd parameters are exactly the opposite, and it's important to note that There's no mistake in Remembering.

For in Traversal object

Loop through the Object's key, which is the key value of the previous one OH

It is generally not recommended to iterate through an array because the for-in traversal does not guarantee the order, and the properties on the prototype chain are traversed, so it is commonly used to traverse Non-array objects and use the hasOwnProperty () method to filter out the properties on the prototype Chain.

var myarry =[1,2,3,4= ' four 'for (varin// Loop key    console.log (value)}//"0"//"1"//  "2"//"3"//"desc" Note The attributes added here are also traversed.

For of Traversal objects

Looping through the values of the object is the value behind the traversal of the Key-value pair, as opposed to the for-in traversal key

var myarry =[1,2,3,4= ' four ';  for (var  value of Myarry) {  console.log (value)}//1//2   3//4
    • This is the simplest and most straightforward syntax for iterating over an array element
    • This method avoids all defects in the for-in cycle.
    • Unlike foreach (), it responds correctly to break, continue, and return statements

JS Foreach,for in, for of

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.