What else do you know if you want to traverse the for loop? Various traversal methods of--javascript

Source: Internet
Author: User
Tags array length terminates


What else do you know if you want to traverse the for loop? Various traversal methods of--javascript


This is an interview in a topic, then I use the current very hot words, the whole person is ignorant, I stayed to say a sentence, I seem to only know for the loop ah. Later back to God, in fact there are many, just for the loop is the most commonly used, we often will not react to the other. Below, through the information you know and find online to do some summary. I hope to be helpful to the people I see.



For convenience, the existing array 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 };




1. For statement


The For statement is the most commonly used loop statement.


1  (function() {
2       for(var i=0, len=demoArr.length; i<len; i++) {
3          if (i == 2) {
4 / / return; / / function execution aborted
5 / / break; / / the loop is terminated
6 continue; / / loop skipped
7           };
8           console.log(‘demo1Arr[‘+ i +‘]:‘ + demo1Arr[i]);
9}
10} (); 


For the For loop, there are a few things to note:


    1. The I in the For loop still exists in scope after the end of the loop, because there is no block-level scope in ECMAScript, even though I is a variable defined inside the loop, it can be accessed outside the loop (JavaScript Advanced programming P57). Therefore, in order to avoid affecting other variables in the scope, the function is self-executing to isolate it () ();
    2. Avoid using the for (var i=0; i<demo1arr.length; i++) {} method, such that the array length is calculated every time, less efficient than the above method. Variable declarations can also be placed in front of the for to perform, improve reading;

      1 var i = 0, len = demo1arr.length; 2 for (; I<len; i++) {};
    3. There are several ways to jump out of a loop
      • Return function execution is terminated
      • Break loop is terminated, exiting the current loop
      • The continue loop is skipped, that is, exiting as a secondary loop, continuing the next cycle
2. for-in Statements


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(var i in demoArr) {
3          if (i == 2) {
4 return; / / function execution is terminated
5 / / break; / / the loop is terminated
6 / / continue; / / loop skipped
7          };
8          console.log(‘demoArr[‘+ i +‘]:‘ + demoArr[i]);
9}
10      console.log(‘-------------‘);
11} (); 





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


  • In the For loop and for in loops, the I value is 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 function res() {
    2     var demoArr = [‘Javascript‘, ‘Gulp‘, ‘CSS3‘, ‘Grunt‘, ‘jQuery‘, ‘angular‘];
    Three
    4     for(var item in demoArr) {
    5         if (item == 2) {
    6             return;
    7};
    8         console.log(item, demoArr[item]);
    9}
    10 console.log ('desc ',' function res'); / / will not execute
    11} 
3. ForEach
Demoarr.foreach (function (ARG) {})


The parameter arg represents the element for each item in the array, with the following example:


1 Demoarr.foreach (function (val, index) {2 if (e = = ' CSS3 ') {3 return;  Loop is skipped 4 //break;   Error 5 //continue;//error 6 }; 7  Console.log (val, index); 8 })


For foreach, here are a few things 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 of
  • is that you can add a second parameter to an array, and this will point to the array in the callback function. If there is no second argument, this points to the window.

    1 demoArr.forEach(function(val, index) {
    2     if (e == ‘CSS3‘) {
    3 return; / / loop skipped
    4 / / break; / / an error is reported
    5 / / continue; / / an error is reported
    6};
    7     console.log(val, index);
    8}
    

    Although there are many limitations to the Foreach loop in the native, the need to understand him is that Many third-party libraries will extend his approach so that it can be applied in many places, such as angular's tool approach, and the Foreach method, which uses no difference from the native, except that it has no limitations, can be used under IE, or can traverse the object

    1 var newArr = [];
    2 demoArr.forEach(function(val, index) {
    3 this. Push (VAL); / / this here points to newarr
    4}, newArr)
    
4. 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 / / use while directly
2 (function() {
3     var i = 0,
4         len = demoArr.length;
5     while(i < len) {
6         if (i == 2) {
7 / / return; / / function execution aborted
8 / / break; / / the loop is terminated
9 / / continue; / / the loop will be skipped, because the code behind cannot be executed, and the value of I has not been changed, so the loop will always be stuck here. Use caution!!
10         };
11         console.log(‘demoArr[‘+ i +‘]:‘ + demoArr[i]);
12         i ++;
13}
14     console.log(‘------------------------‘);
15} ();
Sixteen
17 // do while
18 (function() {
19     var i = 0,
20         len = demo3Arr.length;
21 do {
22         if (i == 2) {
23 break; / / the loop is terminated
24         };
25         console.log(‘demo2Arr[‘+ i +‘]:‘ + demo3Arr[i]);
26         i++;
27     } while(i<len);
28} (); 
5. $.each
1 $.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, Ele represents a value.


 
 
1 $.each(demoArr, function(e, ele) {
2     console.log(e, ele);
3 })





Output to


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


For $.each, the following points need to be noted:


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

  • The output of this value in the loop is similar to the following


     
    
     
    
    1 console.log(this);
    2 //String {0: "C", 1: "S", 2: "S", 3: "3", length: 4, [[PrimitiveValue]]: "CSS3"}
    3 
    4 console.log(this == ele);
    5 // true 


    For the This value above, traverse the


     
    
    1 $.each(this, function(e, ele) {
    2     console.log(e, ele);
    3 })
    4 
    5 // 0 c
    6 // 1 s
    7 // 2 s
    8 // 4 3


    Why is length and [[Primitivevalue]] not traversed? Suddenly, the answer is found in JavaScript advanced programming, presumably in JavaScript's internal properties, setting the enumerable in the object data property to False


    1 / / view the internal property of length
    2 console.log(Object.getOwnPropertyDescriptor(this, ‘length‘));
    3 // Object {value: 4, writable: false, enumerable: false, configurable: false} 
    
    


    The $ (this) in $.each is different from this one, but the traversal results are the same, and you can print it out in the test code.


6. $ (selecter). each


Designed to traverse Domlist


 
 
1 $(‘.list li‘).each(function(i, ele) {
2     console.log(i, ele);
3     // console.log(this == ele); // true
4     $(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


What else do you know if you want to traverse the for loop? The various traversal methods of the--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.