Sample Code for various traversal methods in JavaScript

Source: Internet
Author: User
For examples, the existing arrays and json objects are as follows: vardemoArr [Javascript, Gulp, CSS3, Grunt, jQuery, angular]; vardemoObj {aaa: Javascript, bbb: Gulp, ccc: CSS3, ddd: Grunt, eee: jQuery, fff: .. 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

You can directly look at the example. It's easy to use too much.

(Function () {for (var I = 0, len = demoArr. length; I
 
  

Pay attention to the for Loop

  • In the for loopiAfter the loop ends, it still exists and is in the scope. To avoid affecting other variables in the scope, use function self-execution to isolate it.()();

  • Avoid usingFor (var I = 0; I Such array length is calculated every time, and the efficiency is lower than the above method. You can also put the variable declaration in front of the for statement to improve readability.

Var I = 0, len = demo1Arr. length; for (; I
    
     
   
  • There are several methods to jump out of the loop:

    • Return function execution terminated

    • The break cycle is terminated.

    • The continue loop is skipped.

Complete instance

For in

for(var item in arr|obj){}It can be used to traverse arrays and objects.

  • When traversing an array, item indicates the index value, and arr indicates the element arr [item] corresponding to the current index value.

  • When traversing an object, item indicates the key value, and arr indicates the value corresponding to the key value. obj [item]

(Function () {for (var I in demoArr) {if (I = 2) {return; // function execution is terminated // break; // The loop is terminated // continue; // The loop is skipped}; console. log ('demoarr ['+ I +']: '+ demoArr [I]);} console. log ('-------------');})();

For in, pay attention to the following points:

  • In the for loop and for in loop,iAll values are retained after the loop ends. Therefore, you can avoid using function self-execution.

  • Use return, break, and continue to exit the loop is consistent with the for loop. However, in the return function body, return indicates that the function execution is terminated, even if it is code outside the loop, or continue to execute. Break only terminates the loop, and the subsequent code will continue to be executed.

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'); // not executed}
ForEach

demoArr.forEach(function(arg) {})

The arg parameter indicates the element of each item in the array. The example is as follows:

DemoArr. forEach (function (e) {if (e = 'css3') {return; // The loop is skipped // break; // error // continue; // error }; console. log (e );})

Note the following:

  • ForEach cannot traverse objects

  • ForEach cannot be used in IE. firefox and chrome implement this method.

  • ForEach cannot use break, and continue jumps out of the loop. when return is used, the effect is the same as when continue is used in the for loop.

Do/while

The specific implementation method of the function is as follows, but it is worth noting that when you use continue, if you put I ++ behind it, the I ++ value will never change, finally, it is in an endless loop. Therefore, be cautious when using do/while.

We do not recommend that you use do/while to traverse arrays.

// Directly use the while (function () {var I = 0, len = demoArr. length; while (I <len) {if (I = 2) {// return; // The function execution is terminated // break; // The loop is terminated // continue; // The loop will be skipped, because the code behind it cannot be executed and the I value has not changed, so the loop will remain stuck here, so use it with caution !! }; Console. log ('demoarr ['+ I +']: '+ demoArr [I]); I ++;} console. log ('------------------------');}) (); // do while (function () {var I = 0, len = demo3Arr. length; do {if (I = 2) {break; // The loop is terminated}; console. log ('demo2arr ['+ I +']: '+ demo3Arr [I]); I ++;} while (I
      
       
$. Each
       

$.each(demoArr|demoObj, function(e, ele))

It can be used to traverse arrays and objects. e indicates the index value or key value, and ele indicates the value.

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

The output is

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

There are many things to be aware.

  • UsereturnOrreturn trueTo skip a loop, continue executing the following Loop

  • Usereturn falseTo terminate the execution of the loop, but does not terminate the function execution

  • You cannot use break or continue to skip a loop.

  • The output of this value in a 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 above this value, traverse it.

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

Why is the length and [[PrimitiveValue] Not traversed? Suddenly, I found the answer in "javascript advanced programming", which means that in the internal property of javascriptEnumerableSet to false

// View the internal property console of length. log (Object. getOwnPropertyDescriptor (this, 'length'); // Object {value: 4, writable: false, enumerable: false, retriable: false}

In $. each$(this)It is different from this, but the traversal result is the same. You can print it out in the test code.

$ (Selecter). each

Used 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 the currently traversed DOM elements

  • This is the currently traversed DOM element and cannot call the jQuery method.

  • $ (This) = $ (ele) jquery object of the element currently traversed. You can call jquery to perform dom operations.

Use for in to traverse DOMList

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

var domList = document.getElementsByClassName('its');for(var item in domList) {    console.log(item, ':' + domList[item]);}// 0: 
  • // 1:
  • // ...// length: 5// item: function item() {}// namedItem: function namedItem() {}

    Therefore, when we use for in to traverse domList, we need to convert domList to an array.

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

    Such an object also has the function attribute arguments object. Of course, the string can also be traversed, but because of other attributes of the stringenumerableIs set to false, so the result of traversal is the same as the array, so you don't have to worry about this problem.

    Small supplement

    If you find that some people write functions like this, don't panic or think that he is too tall to be able to afford it.

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

    ()(),!function() {}() +function() {}()Three methods of self-execution of functions ^_^

    The above is a detailed explanation of the sample code for various traversal methods in JavaScript. For more information, see other related articles in the first PHP community!

    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.