15 kinds of loop traversal of js, how many have you mastered?

15 kinds of loop traversal of js, how many have you mastered?

Method 1: Native js loop

1.while loop:

The While statement includes a loop condition and a block of code. As long as the condition is true, the code block will be executed continuously.

syntax:

while (condition) {

Statement;

}

//or while (condition) statement;//for example:

var i = 0; 
while (i <100) { 
    console.log('i is currently:' + i);
    i = i + 1; 
}

2. do……while loop

The do...while loop is similar to the while loop. The only difference is that the loop body is run once, and then the loop conditions are judged.

syntax:

do statement while (condition);//or do {statement} while (condition);//Example:

var x = 3;
var i = 0; 
do { 
    console.log(i); i++; 
} while(i <x);

3. For loop:

for(var i=0;i<filterarray.length;i++){
    alrt(filterarray[i]);
}

4. Enhance the for...in... loop:

Note: fo...in loops are generally used for traversal of objects, but there is a pit that needs attention:

Any object inherits the Object object, or other objects. The properties of the inherited class are not traversable by default .... It will be skipped when the for in loop is traversed, but this property can be changed to traversable, then it will cause the traversal to An attribute that does not belong to itself.

For example, objects inherit toStringproperties, but the for...inloop will not traverse to this property.

    var obj = {};//The toString attribute is the existing obj.toString 
   //toString() {[native code]}
    for (var p in obj) { 
         console.log(p);
    }//No output

If the inherited property is traversable, it will be for...inlooped to. But if you only want to traverse its own properties, for...inwhen using it, you should combine the usage hasOwnPropertymethods to judge whether a certain property is an object's own property or not in the loop. Otherwise, traversal distortion can occur.

    var person = {name:'Lao Zhang' };
    for (var key in person) {  
        if (person.hasOwnProperty(key)) {   
             console.log(key);
          }
    }//name

In addition, the for loop to traverse the json object is a bit weird:

Irregular json array:

 var json = [{dd:'SB',AA:'Dongdong',re1:123}, 
        {cccc:'dd',lk:'1qw'}];

    for(var i=0,l=json.length;i<l;i++){
        for(var key in json[i]){
        alrt(key+':'+json[i][key]);
        }
    }

Why should l=json.length;i<l? Think about it for yourself! Hahahaha...

Regular json array:

  packJson = [
        {"name": "nikita", "password": "1111"},
        {"name": "tony", "password": "2222"}
    ];
 
    for (var p in packJson) {
       //When traversing the json array, write p as the index, 0,1
        alrt(packJson[p].name + "" + packJson[p].password);
    }

5.map() loop:

The map method passes all the members of the array to the parameter function in turn, and then returns the result of each execution as a new array.

Note: It returns a new array without changing the original array.

 var numbers = [1, 2, 3];
     numbers.map(function (n) { 
         return n + 1; 
     }); 
   //[2, 3, 4] 
    numbers//[1, 2, 3]

The map method accepts a function as a parameter. When the function is called, the map method passes three parameters to it: the current member, the current position, and the array itself.

[1, 2, 3].map(function(elem, index, arr) { 
    return elem * index; 
}); 
//[0, 2, 6]

In addition, the map() loop can also accept a second parameter, which is used to bind the this variable inside the callback function, point the this object inside the callback function to the second parameter, and indirectly manipulate this parameter (usually an array).

var arr = ['a','b','c'];

[1, 2].map(function (e) {
    return this[e];
}, arr)
//['b','c']

The above code uses the second parameter of the map method to point the this object inside the callback function to the arr array. Indirectly manipulated the array arr; forEach also has this function.

6.forEach loop

The forEach method is very similar to the map method. It also executes the parameter function sequentially on all members of the array. However, the forEach method does not return a value and is only used to manipulate data. In other words, if the purpose of array traversal is to get the return value, then use the map method, otherwise use the forEach method. The usage of forEach is consistent with the map method. The parameter is a function, and the function also accepts three parameters: current value, current position, and the entire array.

function log(element, index, array) {
     console.log('[' + index +'] = '+ element); 
};
[2, 5, 9].forEach(log);//[0] = 2//[1] = 5//[2] = 9

In addition, the forEach loop, like the map loop, can also use the this variable inside the bound callback function to indirectly manipulate other variables (refer to the map() loop example above).

7.filter() filter loop

The filter method is used to filter the members of the array, and the members that meet the conditions form a new array and return. Its parameter is a function, all array members execute the function in turn, and the members whose return result is true form a new array to return. This method will not change the original array.

[1, 2, 3, 4, 5].filter(function (elem) {
     return (elem> 3); 
})//[4, 5]

//The above code returns array members greater than 3 as a new array.
var arr = [0, 1,'a', false]; 
arr.filter(Boolean)//[1, "a"]

The parameter function of the filter method can also accept three parameters: the current member, the current position and the entire array.

    [1, 2, 3, 4, 5].filter(function (elem, index, arr) { 
        return index% 2 === 0; 
    });//[1, 3, 5]

In addition, the filter method can also accept a second parameter, which is used to bind the this variable inside the parameter function.

var obj = {MAX: 3 }; var myFilter = function (item) {
     if (item> this.MAX) return true; 
}; 
var arr = [2, 8, 3, 4, 1, 3, 2, 9]; 
arr.filter(myFilter, obj)//[8, 4, 9]

8. Some (), every () loop traversal, statistics whether the array meets a certain condition

These two methods are similar to "assert" and return a Boolean value, which means to determine whether the array members meet a certain condition.

They accept a function as a parameter, and all array members execute the function in turn. This function accepts three parameters: the current member, the current position and the entire array, and then returns a Boolean value.

someThe method is that as long as the return value of a member is true, the return value of the entire somemethod is true, otherwise it returns false.

  var arr = [1, 2, 3, 4, 5];
    arr.some(function (elem, index, arr) {
          return elem >= 3;
        }); 

       //true 

and everyThe method is the opposite, the return value of all members is the same true, the entire everymethod returns true, otherwise it returns false. Comparing the two, as long as one of some() is true, it returns true; and as long as one of every() is false, it returns false.

     var arr = [1, 2, 3, 4, 5];
        arr.every(function (elem, index, arr) {
          return elem >= 3;
        });
       //false

These two methods are very useful in actual development. For example, you can use these two methods to traverse the loop array when determining whether the user has checked inoperable data, or whether the user has checked an operable data.

9. reduce(), reduceRight() methods can process each member of the array in turn

reduceMethods and reduceRightmethods process each member of the array in turn, and finally accumulate to a value. The difference between them is that they reduceare processed from left to right (from the first member to the last member), reduceRightand from right to left (from the last member to the first member), and everything else is exactly the same.

 [1, 2, 3, 4, 5].reduce(function (a, b) {
      console.log(a, b);
      return a + b;
    })
   //1 2
   //3 3
   //6 4
   //10 5
   //Final result: 15

reduceThe method and reduceRightthe first parameter of the method are both a function. The function accepts the following four parameters.

  1. Cumulative variable, the default is the first member of the array
  2. The current variable, the default is the second member of the array
  3. Current position (starting from 0)
  4. Original array

Among these four parameters, only the first two are required, and the last two are optional.

If you want to specify the initial value of the cumulative variable, you can put it in the reducemethod and reduceRightthe second parameter of the method.

   [1, 2, 3, 4, 5].reduce(function (a, b) {
      return a + b;
    }, 10);
   //25

The second parameter above is equivalent to setting a default value, which is especially useful when dealing with empty arrays to avoid some null pointer exceptions.

Since these two methods will traverse the array, they can actually be used to do some traversal-related operations. For example, find the array member with the longest character length.

   function findLongest(entries) {
          return entries.reduce(function (longest, entry) {
               return entry.length> longest.length? entry: longest;
          },'');
    }
findLongest(['aaa','bb','c'])//"aaa"

In the above code, reducethe parameter function will take the array member with the longer character length as the cumulative value. This causes the cumulative value to be the member with the longest character length after traversing all the members.

10.Object, keys traverse the properties of the object

Object.keysThe parameter of the method is an object, which returns an array. The members of the array are all property names of the object itself (not inherited), and only enumerable properties are returned.

   var obj = {
      p1: 123,
      p2: 456
    };

    Object.keys(obj)//["p1", "p2"]

11. Object.getOwnPropertyNames()Traverse the properties of the object

Object.getOwnPropertyNamesThe method is Object.keyssimilar. It also accepts an object as a parameter and returns an array containing all the attribute names of the object itself. But it can return non-enumerable properties.

 var a = ['Hello','World'];

    Object.keys(a)//["0", "1"]
    Object.getOwnPropertyNames(a)//["0", "1", "length"]

In the above code, the lengthproperties of the array are non-enumerable properties, so they only appear in Object.getOwnPropertyNamesthe return result of the method.

Since JavaScript does not provide a method for calculating the number of object properties, these two methods can be used instead.

 var obj = {
      p1: 123,
      p2: 456
    };
    Object.keys(obj).length//2
    Object.getOwnPropertyNames(obj).length//2

The above cycle characteristics (same and different):

One: map(), foreach, filter loops have in common:

1. The foreach , map, and filter loops cannot be stopped in the middle, and all members are always traversed.

2. They can all accept the second parameter, which is used to bind the this variable inside the callback function, point the this object inside the callback function to the second parameter, and indirectly manipulate this parameter (usually an array).

Two: the difference between map() loop and forEach loop:

The forEach loop has no return value; the map and filter loops have return values.

Three: map () loop, forEach loop and filter () loop will skip the gap, for and while will not

    var f = function (n) { 
        return'a' 
    }; 

    [1, undefined, 2].map(f)//["a", "a", "a"] 
    [1, null, 2].map(f)//["a", "a", "a"]
    [1,, 2].map(f)//["a",, "a"]

In the above code, the map method will not skip undefined and null, but will skip empty spaces. The forEach method will also skip the empty positions of the array, so I won't give an example here.

Four: some() andevery():

As long as one of some() is true, it returns true; and as long as one of every() is false, it returns false.

Five: reduce(), reduceRight():

reduceIt is processed from left to right (from the first member to the last member), reduceRightand from right to left (from the last member to the first member).

Six: Two traversals of Object objects Object.keys versus Object.getOwnPropertyNames:

They are all traversal object properties, Also accepts an object as a parameter, and returns an array containing all the attribute names of the object itself. But it Object.keyscannot return non-enumerable properties; it Object.getOwnPropertyNamescan return non-enumerable properties.

Method 2: Traversal using JQuery:

1. $.grep() filter and traverse the array

The grep() loop can traverse the array, and select the elements that meet the conditions, form a new array, and return.

function(){

    var array = [1,2,3,4,5,6,7,8,9];

    var filterarray = $.grep(array,function(value){
        return value> 5;//Filter out those greater than 5
    });

    for(var i=0;i<filterarray.length;i++){
        alrt(filterarray[i]);
    }

    for (key in filterarray){
        alrt(filterarray[key]);
    }

}

2.$.each() filter and traverse arrays or json objects

function(){ var anObject = {one:1,two:2,three:3};//To json array each .each(anObject,function(name,value) {alrt(name); alrt(value);} ); var anArray = ['one','two','three']; .each(anArray,function(n,value){ alrt(n); alrt(value); });

}

3.$.inArray() filter and traverse the array

The inArray() loop can return the coordinates of the parameter in the array.

    function(){

        var anArray = ['one','two','three'];
        var index = $.inArray('two',anArray);

        alrt(index);//Return the key value of the value in the array, return 1
        alrt(anArray[index]);//value is two
    }

4.$.map() filter and traverse the array

Map loop common language to add new elements to the array, the second way of writing:

().ready( function(){ var strings = ['0','1','2','3','4','S','6']; var values ​​= .map(strings, function(value){ var result = new Number(value); return isNaN(result)? null:result;//isNaN:is Not a Number abbreviation}); for (key in values) {alrt(values[key] ); }});

map() passes each element to the current matching set through a function, and generates a new jQuery object containing the return value. This usage is consistent with the map cycle usage of native js.

Hahahaha, dear classmates, do you feel a lot? In fact, don't memorize it specially. I personally suggest native for loops, forEach loops, and Juery's each familiarity.