A detailed description of JavaScript traversal methods

Source: Internet
Author: User
Tags terminates

In $.each you want to terminate the loop, but it does not have a terminating mode such as continue or break, so try to use return to terminate, but the discovery does not jump out of the loop. In order to figure out the different types of traversal in JS, through the query to make a summary:

For the convenience of examples, the existing arrays and JSON objects are as follows:

1 var demoarr = [' Javascript ', ' Gulp ', ' CSS3 ', ' Grunt ', ' jQuery ', ' angular ']; 2 var demoobj = {3     AAA: ' Javascript ',4     bbb: ' Gulp ', 5     CCC: ' CSS3 ',6     ddd: ' Grunt ',7     eee: ' jQuery ',  8     FFF: ' Angular '9 };

For

Usually use the most, see the case directly

1(function() {2      for(varI=0, Len=demoarr.length; i<len; i++) {3         if(i = = 2) {4             //return; function execution is terminated5             //Break ; Loop is terminated6             Continue;//The loop is skipped.7         };8Console.log (' demo1arr[' + i + '): ' +demo1arr[i]);9     }Ten})();

For the For loop, there are a few points to note

    • The For loop is i still present in the scope after the loop ends, and in order to avoid affecting other variables in the scope, it is isolated by the way the function is self-executing ()() ;
    • Avoid usingfor(var i=0; i<demoArr.length的方式,这样的数组长度每次都被计算,效率低于上面的方式。也可以将变量声明放在for的前面来执行,提高阅读性。

There are several ways to jump out of a loop

    • Return function execution is terminated
    • Break loop is terminated
    • Continue loop is skipped

  

For in

for(var item in arr|obj){}Can be used to iterate over arrays and objects

    • When iterating through an array, item represents the index value, and arr represents the element that corresponds to the current index value Arr[item]
    • When traversing an object, item represents the key value, and arr represents the value of the key value Obj[item]
1(function() {2      for(varIinchDemoarr) {3         if(i = = 2) {4             return;//function execution is terminated5             //Break ; Loop is terminated6             //continue; The loop is skipped.7         };8Console.log (' demoarr[' + i + '): ' +demoarr[i]);9     }TenConsole.log ('-------------'); One})();

There are a few things to note about the for in:

    • In the For loop and for in loops, the i values are preserved after the loop ends. Therefore, the function is self-executing in a way that avoids it.
    • Using Return,break,continue to jump out of the loop is consistent with the For loop, but it is important to note that in the function body, return means that the function terminates, even if the code outside the loop does not continue to execute. The break simply terminates the loop, and the subsequent code will continue to execute.
1 functionRes () {2     varDemoarr = [' Javascript ', ' Gulp ', ' CSS3 ', ' Grunt ', ' jQuery ', ' angular '];3  4      for(varIteminchDemoarr) {5         if(Item = = 2) {6             return;7         };8 Console.log (item, Demoarr[item]);9     }TenConsole.log (' desc ', ' function res ');//does not execute One}

Foreach

demoArr.forEach(function(arg) {})
The parameter arg represents the element for each item in the array, as an example

 1  Demoarr.foreach (function   (val, index) { 2  if  (E = = ' CSS3 ') Span style= "color: #000000;"  ) { 3  return ; //  loop is skipped  4     Break Error  5  //  continue;//error  6  };  7   Console.log (val, index);  8 }) 

In particular, there are the following areas to note

    • There are 2 parameters in the callback function that represent values and indexes, which are the opposite of $.each in jquery.
    • foreach cannot traverse object
    • foreach cannot be used in IE, Firefox and Chrome implement this method
    • foreach cannot jump out of a loop using Break,continue, and with return, the effect is consistent with the use of continue in the For loop
    • The most important point is that you can add a second parameter to an array, and the this in the callback function points to the array. If there is no second argument, this points to the window.
1 var newArr = []; 2 Demoarr.foreach (function(val, index) {3This     //  Here's this point to NewArr4 }, NEWARR)

Although there are many limitations to the Foreach loop in the native, it is necessary to understand that many third-party libraries will extend his approach so that it can be applied in many places, such as angular's tool methods, as well as the Foreach method, whose use is no different from that of the native, but without limitations , can be used under IE, can also traverse the object

1 var result = []; 2 function (val, index) {3      This . push (Val); 4 }, result);
Do/while

The implementation of the function is as follows, but it is worth noting that when using continue, if you put i++ behind, then the value of i++ will not change, and finally into a dead loop. So use do/while must be careful.

It is not recommended to use the Do/while method to iterate through an array

1 //Direct Use while2(function() {3     vari = 0,4Len =demoarr.length;5      while(I <Len) {6         if(i = = 2) {7             //return;//function execution is terminated8             //Break ; Loop is terminated9             //continue; The loop will be skipped, because the code behind cannot be executed, the value of I has not changed, so the loop will always be stuck here, use caution!! Ten         }; OneConsole.log (' demoarr[' + i + '): ' +demoarr[i]); Ai + +; -     } -Console.log ('------------------------'); the })(); -   - // Do While -(function() { +     vari = 0, -Len =demo3arr.length; +      Do { A         if(i = = 2) { at              Break;//loop is terminated -         }; -Console.log (' demo2arr[' + i + '): ' +demo3arr[i]); -i++; -} while(i<len); -})();

$.each

$.each(demoArr|demoObj, function(e, ele))
Can be used to iterate over arrays and objects, where E represents an index value or a key value, and Ele represents the value

1 function (E, ele) {2    console.log (E, ele); 3 })

Output to

0 "Javascript" 1 "Gulp" 2 "CSS3" 3 "Grunt" 4 "jQuery" 5 "angular"

There's a lot to be aware of here.

    • Use return or to return true skip a loop and continue with the following loop
    • Used return false to terminate the execution of a loop, but does not terminate function execution
    • Cannot use break with continue to skip loops

$ (selecter). each

Designed to traverse Domlist

1$ ('. List Li '). each (function(i, ele) {2 Console.log (i, ele);3     //Console.log (This = = Ele);//True4$( This). html (i);5     if($( This). attr (' data-item ') = = ' Do ') {6$( This). HTML (' Data-item:do ');7     };8})
    • I: Sequence value ele: Only DOM element that is currently traversed
    • This is currently traversed by the DOM element and cannot be called by the jquery method
    • $ (this) = = $ (ele) The JQuery object that is currently traversing the element, can invoke the JQuery method for DOM operation
Using the for in traversal domlist

Because Domlist is not an array, it is an object, just because its key value is 0,1,2 ... The feeling is similar to the array, but the result of the direct traversal is as follows

1 varDomlist = Document.getelementsbyclassname (' its ');2  for(varIteminchdomlist) {3Console.log (item, ': ' +Domlist[item]);4 }5 //0:6 //1:7 //    ...8 //Length:59 //item:function Item () {}Ten //nameditem:function Nameditem () {}

So we need to convert the domlist to an array when we use the for in traversal of the domlist

1 var res = [].slice.call (domlist); 2  for (var in res) {}

  

There are three ways to increase the self-executing function of the force lattice: ()() , !function() {}() +function() {}()

A detailed description of JavaScript traversal methods

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.