First, the method of realizing the loop traversal

Native JS implementation traversal:

1. While

The While statement consists of a loop condition and a block of code that executes over and over again as long as the condition is true.

while(condition) {execute code; };Copy the code

2. do… While

do… A while loop is similar to a while loop, except that the body of the loop is run once and then the condition is judged.

do{execute code; }while(conditions);Copy the code

3. for

Common for loop, often used array traversal. Use temporary variables to cache the length and avoid fetching the array length repeatedly. The optimization effect is more obvious when the array is large.

for(j = 0; j < arr.length; j++) {
    // Code execution
}
Copy the code

4. for … in

The for… In loops are generally used for traversing objects, not for traversing groups of numbers.

But there is a catch: any Object inherits Object, or any other Object, and the attributes of the inherited class are not traversable by default, for… The in loop skips it, but the property can be changed to be traversable, resulting in traversal of properties that do not belong to it.

var obj = {a: 1.b: 2.c: 3}; 

for (var i in obj) { 
    console.log('key name:', i); 
    console.log('Key:', obj[i]); 
} 
Key name: a key value: 1 Key name: b key value: 2
// obj is the object of the loop, and I is the "key name" in the object. If the object is an array, then I is the index.
Copy the code

If the inherited property is traversable, it will be for… In loops through to. But if you just want to iterate over your own properties, use for… When in, you should use the hasOwnProperty() method to check inside the loop whether an attribute is a property of the object itself. Otherwise, ergodic distortion can occur.

Disadvantages of traversing arrays: array index is a number, for-in traversing index “0”,”1″,”2″, etc., are strings.

5. for … of

for… Of traversal is a new feature in ES6

for( let i of arr){
    console.log(i);
}
Copy the code

for… The OF loop supports not only arrays, but also most array-like objects, as well as string traversal. for… Of responds correctly to break, continue, and return statements.

6. forEach

The main function is to iterate over groups of numbers, and the actual performance is weaker than for.

arr.forEach(function(item, index){
  console.log('forEach traversal:' + index + The '-' + item);
})
Copy the code

ForEach cannot break the loop with a break statement, nor can it return to the outer function with a return statement.

7. map()

The map() method passes all the members of the array to the argument function in turn and returns the result of each execution as a new array.

arr.map(function(value, index){
    console.log('the map traversal:' + index + The '-' + value);
});	 
// Map traversal supports return statements and return values
var temp = arr.map(function(val, index){
  console.log(val); 
  return val * val;          
})
console.log(temp);
Copy the code

Note: map() returns a new array and does not alter the original array.

8. filter()

The filter() method is used to filter the members of an array, and the members that meet the criteria are returned as a new array. It takes a function that all array members execute in turn, returning true members as a new array. This method does not change the original array.

var arr = [73.84.56.22.100];
var newArr = arr.filter(item= > item>80)
// Get the new array newArr = [84, 100].
Copy the code

9. every()

Every () runs the specified function on each item in the array to determine whether the members of the array meet certain conditions. If the function returns true for each item, it returns true.

var arr = [ 1.2.3.4.5.6 ]; 
arr.every( function( item, index, array ){ 
    return item > 3; 
}); 
// false
Copy the code

10. some()

Some (), as opposed to every(), returns true if the function returns true for any item, and false otherwise.

var arr = [ 1.2.3.4.5.6 ]; 
arr.every( function( item, index, array ){ 
    return item > 3; 
}); 
// true
Copy the code

Some () returns true as long as either of them is true; Every () returns false as long as one of them is false.

11. The reduce () and reduceRight ()

The reduce() method and reduceRight() method receive a function as an accumulator, which has four parameters: last value, current value, index of current value, and array. The difference is that reduce() is processed from left to right (first member to last member), reduceRight() is processed from right to left (last member to first member), and everything else is exactly the same.

var total = [0.1.2.3.4];
Of these four parameters, only the first two are required, while the last two are optional.
total.reduce(function( previousValue, currentValue){
    return previousValue + currentValue;
});
// If you want to specify an initial value for the cumulative variable, you can place it in the second argument to the reduce and reduceRight methods.
total.reduce(function( a, b){
    return a + b;
}, 10);
// The second argument above sets the default value, which is especially useful when dealing with empty arrays and can avoid some null pointer exceptions.
Copy the code

12. find()

The find() method returns the first element in the array that matches the function’s criteria. Otherwise return undefined.

var stu = [{ name: 'Joe'}, {name: 'Wang Xiaomao'}, {name: 'bill'.age: 18}]
stu.find((item) = > (item.name === 'bill')) 
// {name: "li ", age: 18}
Copy the code

13. findIndex()

The findIndex() method calls the callback once (in ascending index order) for each element in the array until any element returns true. As soon as one element returns true, findIndex() returns the index of the element that returns true. If no element in the array returns true, findIndex() returns -1.

FindIndex () does not change the array object.

[1.2.3].findIndex(x= > x === 2 );  / / 1
[1.2.3].findIndex(x= > x === 4 );  // -1
Copy the code

14. ES6 new: Entries (), keys() and values()

Entries (), keys() and values() — For traversing groups of numbers. They both return a traverser object, which can be used for… The of loop iterates.

The only differences are that keys() is traversal of key names, values() is traversal of key values, and entries() is traversal of key value pairs.

// traversal of keys()
for (let i of ['a'.'b'].keys()) {
    console.log(i);  / / 0 to 1
}
// values() key traversal
for (let item of ['a'.'b'].values()) {
    console.log(item);  // a b
}
// Entries key-value pair traversal
for (let [index, item] of ['a'.'b'].entries()) {
    console.log(index, item);
    // 0 "a" 1 "b"
}
Copy the code

JQuery implements traversal:

1. jQuery.grep()

The $.grep() function uses the specified function to filter the elements in the array and filter the qualified elements to form a new array and return.

var arr = [ 1.9.3.8.6.1.5.9.4.7.3.8.6.9.1 ];
arr = jQuery.grep(arr, function( item, index ) {
// function takes the element of the current iteration and the index of the element in the current iteration.
     if( item ! = =5 && index > 4) {// Return an array with a non-5 element and an index greater than 4
       return true; }});console.log(arr) // (9) [1, 9, 4, 7, 3, 8, 6, 9, 1]
Copy the code

2. jQuery.each()

The $.each() function iterates through the specified object and array.

jQuery.each([52.97].function(index, value) {
    console.log(index + ':' + value);
    // 0:52 // 1:97
});
Copy the code

3. jQuery.inArray()

The $.inarray () function looks for the specified value in the array and returns its index (-1 if none is found).

var anArray = ['one'.'two'.'three'];
var index = $.inArray('two', anArray);
console.log(index); // Returns the key value in the array, which returns 1
console.log(anArray[index+1]); // three
Copy the code

4. jQuery.map()

The $.map() function is used to process each element in an array (or each property of an object) with the specified function and return the result as a new array.

$(function () { 
    var arr = ['0'.'1'.'2'.'3'.'4'.'S'.'6'];
    var values = $.map(arr, function(value){
    var result = new Number(value);
        return isNaN(result) ? null : result; // Return result if it is not NaN
    });
    // Iterate over printing the newly returned values
    for (key in values) {
        console.log(values[key]) // 0, 1, 2, 3, 4, 6}})Copy the code

2. Performance comparison of common loop traversal methods

Here we compare the performance of several common methods: normal for loop, reverse for loop, while loop, for-in loop, for each loop, and Duff’s Device loop.

Even the fastest code in the loop can slow down by iterating thousands of times. In addition, there is a small performance overhead when the loop body is running, not least by increasing the overall run time. Reducing the number of iterations leads to more significant performance gains, and one of the most well-known patterns for limiting the number of iterations of a loop is known as “Duff’s Device.”

var num = 10000;  // Array size
var itemNum = 1000;  // Number of iterations 100/1000/10000/100000
var array = [];  // Initialize the array
for (var i = 0 ; i < num ; i++ ){
    array[i] = i + 1;
}
var len = array.length;

console.log("Number of iterations: + itemNum);

// Normal for loop
console.time('Normal for loop');
for(var j = 0 ; j < itemNum ; j ++) {
    for(var k = 0 ; k < len ; k ++) {
        array[k] + 1; }}console.timeEnd('Normal for loop');


// Reverse for loop
console.time('Reverse for loop');
for(let j = 0; j < itemNum; j ++){
    for(let k = len - 1 ; k --;)
    {
        array[k] + 1; }}console.timeEnd('Reverse for loop');


/ / while loop
console.time('while loop');
for(let j = 0; j < itemNum; j ++){   
    let k = 0;
    while(k < len){
        array[k] + 1; k ++; }}console.timeEnd('while loop');


/ / the for - in circulation
console.time('the for - cycle in');
for(let j = 0; j < itemNum; j ++){
    for(let k in array){
        array[k] + 1; }}console.timeEnd('the for - cycle in');


// for each
console.time("The for-each loop");
for(let j =0; j <itemNum; j ++){
    array.forEach((item) = > {
        item + 1;
    });
}
console.timeEnd("The for-each loop");


// Duff's Device algorithm is a loop body unwrapping technique that allows multiple iterations to be performed in one iteration.
console.time("Duff's Device");
for(let k = 0; k < itemNum; k ++){
    let j = len % 8;
    let tempLen = len-1;
    while(j){
        j--;
        array[tempLen--] + 1;
    }
    j = Math.floor(len / 8);
    while(j){
        j--;
        array[tempLen --] + 1;
        array[tempLen --] + 1;
        array[tempLen --] + 1;
        array[tempLen --] + 1;
        array[tempLen --] + 1;
        array[tempLen --] + 1;
        array[tempLen --] + 1;
        array[tempLen --] + 1; }}console.timeEnd("Duff's Device");
Copy the code

By iterating through each loop and printing the running time of each mode, you can find:

  • In general, the for loop performs as well as for-each, and as well as while for small amounts of data. For-in has the worst performance, while Duff’s device has the best performance. For large amounts of data, while performs better than for loops and for-each loops.
  • For loops with small data volumes (<1000), there is no need to consider which one is better; readability is the first priority.
  • For loops and traversals with large amounts of data, if performance is not a bottleneck, plain for loops (or while, do-while, for-each) will do, since they are readable.
  • For large volumes of data, if the looping of an Array is a bottleneck, or if performance is critical, the Duff’s Device solution can be used.
    • The basic idea behind Duff’s Device is that the execution function can be called up to eight times per loop. The number of iterations of the loop is the total number of elements divided by 8. Since the total is not necessarily an integer multiple of 8, the variable j is declared to store the remainder, indicating how many times the first loop should be executed. For example, if you now have 12 elements, the first loop calls the executing function 4 times and the second loop calls the executing function 8 times, with 2 loops instead of 12.
    • How this scheme is used depends largely on the number of iterations. If the loop iterates less than 1000 times, you may only see a negligible performance improvement over a normal loop. The efficiency of Duff’s device increases significantly if the number of iterations exceeds 1000. For example, in 500,000 iterations, the running time is reduced to 70% compared to a normal loop.

Reference article: www.cnblogs.com/libin-1/p/6… Blog.csdn.net/cengjingcan…