A detailed description of JavaScript traversal methods

Source: Internet
Author: User
Tags terminates

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

var Demoarr = [' JavaScript ', ' Gulp ', ' CSS3 ', ' Grunt ', ' jQuery ', ' angular '];var demoobj = {    AAA: ' JavaScript ',    BBB: ' Gulp ',    CCC: ' CSS3 ',    ddd: ' Grunt ',    eee: ' jQuery ',    FFF: ' Angular '};
For

Can look at the example directly, using too much, very simple

(function () {    for (var i=0, len=demoarr.length; i<len; i++) {        if (i = = 2) {            //return;   function execution is terminated            //break;    The loop is terminated            continue;//cycle is skipped        };        Console.log (' demo1arr[' + i + ']: ' + demo1arr[i]);}    }) ();

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 using for(var i=0; i<demo1Arr.length; i++){} the way that the array length is calculated every time, less efficient than the above method. You can also put the variable declaration in front of the for to improve the readability of the
var i = 0, len = demo1arr.length;for (; i<len; i++) {};
    • There are several ways to jump out of a loop
      • Return function execution is terminated
      • Break loop is terminated
      • Continue loop is skipped

Full instance

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]
(function () {for    (var i in Demoarr) {        if (i = = 2) {            return;//function execution is terminated            //break;  Cycle is terminated            //continue;  Loop is skipped        };        Console.log (' demoarr[' + i + ']: ' + demoarr[i]);    }    Console.log ('-------------');}) ();

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.
function res () {    var demoarr = [' Javascript ', ' Gulp ', ' CSS3 ', ' Grunt ', ' jQuery ', ' angular '];    For (var item in Demoarr) {        if (item = = 2) {            return;        };        Console.log (item, Demoarr[item]);    }    Console.log (' desc ', ' function res '); Does not execute}
Foreach

demoArr.forEach(function(arg) {})

The parameter arg represents the element for each item in the array, as an example

Demoarr.foreach (function (e) {    if (e = = ' CSS3 ') {        return;  Loop is skipped        //break;   Error        //continue;//error    };    Console.log (e);})

In particular, there are the following areas to note

    • 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
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

Direct use while (function () {    var i = 0,        len = demoarr.length;    while (I < len) {        if (i = = 2) {            //return;//function execution is terminated            //break;  Cycle is terminated            //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!!        };        Console.log (' demoarr[' + i + ']: ' + demoarr[i]);        i + +;    }    Console.log ('------------------------');}) ();//Do While (function () {    var i = 0,        len = demo3arr.length;    Do {        if (i = = 2) {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

$.each (Demoarr, function (e, ele) {    console.log (e, ele);})

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
    • The output of this value in the loop is similar to the following
Console.log (this);//string {0: "C", 1: "S", 2: "S", 3: "3", Length:4, [[Primitivevalue]]: "CSS3"}console.log (this = = Ele) ;//True
    • For the This value above, traverse the
$.each (this, function (E, ele) {    console.log (e, ele);}) 0 c//1 s//2 s//4 3

Why is length and [[Primitivevalue]] not traversed? A sudden epiphany, found in JavaScript advanced programming, probably means that the internal properties of JavaScript will set the object Data property Enumerable to False

View the internal properties of length Console.log (Object.getownpropertydescriptor (this, ' length '));//Object {value:4, Writable:false, Enumerable:false, Configurable:false}

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

$ (selecter). each

Designed to traverse Domlist

$ ('. List Li '). each (function (i, ele) {    Console.log (i, ele);    Console.log (This = = Ele); True    $ (this). HTML (i);    if ($ (this). attr (' data-item ') = = ' do ') {        $ (this). html (' Data-item:do ');}    )
    • 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

var domlist = document.getelementsbyclassname (' it '); for (var item in domlist) {    console.log (item, ': ' + domlist[item ]);} 0: <li></li>//1: <li></li>//    ...//length:5//item:function item () {}//nameditem:funct Ion Nameditem () {}

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

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

Objects like this also have the properties of the function arguments object, of course, the string can also be traversed, but because the string other properties are enumerable set to false, so the result of the traversal is the same as the array, there is no need to worry about this problem.

Small supplement

If you find some people writing functions like this, don't panic, don't think he's big on the bird

+function (ROOT, Struct, undefined) {    ...} (window, function () {    function person () {}})

()(), !function() {}() +function() {}() Three functions are self-executing in the way ^_^

A detailed description of JavaScript traversal methods

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.