Summary of various loops in JavaScript

Source: Internet
Author: User

How do we iterate through the elements in the array? 20 years ago when JavaScript was first born, you could implement array traversal like this:

1 var arr=["One", "one", "three"; 2  for (var i=0;i<arr.length;i++) {3    document.write (Arr[i]); 4 }

 

Since ES5 is officially released, you can use the built-in foreach method to iterate through the array:

myArray.forEach(function (value) { console.log(value);});
实际上forEach有三个参数 分别为 值 下标 数组本身 于是我们有
[].foreach (function (value, index, array) {    //...});

Compare the methods in jquery $.each :

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

Will find that the 1th and 2nd parameters are exactly the opposite, we have to pay attention to, do not remember the wrong. A similar approach is followed, for example $.map .

function (i, value) {   array// array this     ;      // This points to the current element      i;          // I represents the array current subscript      value;      // value represents the current element of the array });
var arr = ["One", "one", "three", "four"];       function () {         alert (this);      });      

The results for each of the above outputs are: One,two,three,four

var obj = {one:1, two:2, Three:3, Four:4};      function (Key, Val) {         alert (Obj[key]);           });   

This each one is more powerful, can loop each property
The output is: 1 2 3 4


例如:
Arr.foreach (function(i,j,v) {    document.write ("<br/> Array Value" +i+                     "<br/> Array Subscript" + J+ "," +                     "<br/> Array itself" +v+ "---")})

This code looks more concise, but there is a small flaw in this approach:

foreach is not flexible enough

Arr.foreach not good for you. You cannot use the break statement to interrupt a loop, nor can you use the return statement to return to an outer function.

Of course, it would be nice to iterate through the array elements with only the syntax for the For loop.

Well, you'll want to try the For-in loop:

 for (varin// don't do this   console.log (Myarray[index]);}

In this code, the value assigned to index is not the actual number, but the string "0", "1", "2", it is possible to inadvertently do string arithmetic calculation, for example: "2" + 1 = = "21", which caused great inconvenience to the coding process.

Nutshell

For-in is designed for normal objects, and you can iterate through the keys of the string type, and therefore not for array traversal.

for...inNot suitable for iterating through an array

For...in will traverse through custom properties and even prototype properties, index is a string instead of a numeric value, and in some cases not even sequentially traverse

A powerful for-of cycle

ES6 will not destroy the JS code you have written. For now, thousands of web sites rely on for-in loops, some of which even use them for array traversal. If you want to increase the array traversal support by modifying the for-in loop, it will make all this more confusing, so the standard committee has added a new loop syntax to the ES6 to solve the current problem.

We need a more convenient way to iterate through an array, just as easy to use as for...in traversing an object, which isfor...of

Just like this:

 for (var  value of MyArray) {  console.log (value);}

Yes, does this cycle look familiar compared to the previous built-in approach? Well, we're going to explore what powerful features are hidden beneath the exterior of the for-of loop. Now, just remember:

    • 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

The for-in loop is used to iterate through the object properties.

For-of loops are used to traverse data-for example, values in an array.

But not only that!

For-of loops can also traverse other collections.

The for-of loop supports not only arrays, but also most class array objects, such as Dom NodeList objects.

The for-of loop also supports string traversal, which treats a string as a series of Unicode characters to traverse:

 for (var  value of MyArray) {  console.log (value);}

It also supports map and set object traversal.

$.map(array,function)
Syntax Analysis:Each element in an array of arrays, called the function function for processing, and thenreturn the result to get a new array。 Example Explanation:Returns a new array for each element in the array. The code is as follows

<script Type="Text/javascript" Src="Jquery-1.8.2.min.js"></script>
<script Type="Text/javascript">
VarArr= [2,3,6];
VarArr2=$.Map(Arr,function(Item){ReturnItem*2;});
For(var I=0len=arr2. Length; I<len;++) {
Document. Write (arr2[i]+ "<br/>" ); //result is 4 6
}
</SCRIPT>
span class= "tag" ></HEAD>
</HTML>

Additional notes:Item represents each element, which is a formal parameter, which can be replaced by other.
 
 
 

Summary of various loops in JavaScript

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.