Several ways of JS array traversal

Keywords: Javascript Front-end

JS array traversal is basically for,forin,foreach,forof,map and other methods. The following describes several array traversal methods used in this analysis and performance analysis and comparison

The first is a normal for loop

The code is as follows:

for(j = 0; j < arr.length; j++) {


}

Brief description: the simplest one is also the one with the highest frequency of use. Although the performance is not weak, there is still room for optimization

Second: optimized version for loop

The code is as follows:

for(j = 0,len=arr.length; j < len; j++) {


}

Brief description: use temporary variables to cache the length to avoid repeatedly obtaining the array length. The optimization effect will be more obvious when the array is large.

This method is basically the highest performance of all loop traversal methods

The third is the weakened version of the for loop

The code is as follows:

for(j = 0; arr[j]!=null; j++) {


}

Brief description: in fact, this method strictly belongs to the for loop, but it does not use the length judgment, but the variable itself

In fact, the performance of this method is much lower than that of ordinary for loops

Fourth: foreach loop

The code is as follows:

arr.forEach(function(e){


});

Brief description: the foreach loop of the array is frequently used. In fact, its performance is weaker than that of the ordinary for loop

Fifth: foreach variant

The code is as follows:

Array.prototype.forEach.call(arr,function(el){


});

Brief description: because foreach comes with Array type, some non Array types cannot be used directly (such as NodeList), so this variant is available. Using this variant can make similar arrays have foreach function.

The actual performance is weaker than ordinary foreach

Sixth: forin cycle

The code is as follows:

for(j in arr) {


}

Brief description: this loop is loved by many people, but in fact, after analysis and test, it is used in many loop traversal methods

Its efficiency is the lowest

Seventh: map traversal

The code is as follows:

arr.map(function(n){


});

Brief description: this method is also widely used. Although it is elegant to use, the actual efficiency is not as good as foreach

The eighth type: forof traversal (ES6 support is required)

The code is as follows:

for(let value of arr) {


});

Brief description: this method is used in es6. Its performance is better than forin, but it is still not as good as ordinary for loops

Performance comparison of various traversal modes

Several methods listed above have been compared and analyzed one by one. Basically, the conclusion can be drawn as follows:

Ordinary for loops are the most elegant

(PS: all of the above codes are only empty loops. They do not recycle the internal execution code. They just analyze the time of their loops.)

Performance comparison screenshot

Analysis result 1

The data in the following screenshot is the conclusion obtained after 100 runs in chrome (supporting es6) (10 runs each time, a total of 10 cycles, and the analysis results obtained)  

As you can see, the forin loop is the slowest. The optimized ordinary for loop is the fastest

Analysis result 2

The following screenshot data is the conclusion obtained after 1000 runs in chrome (supporting es6) (100 runs each time, a total of 10 cycles, and the analysis results)  

   1. javascript The common traversal methods for traversal are for loop and for in. The forEach method is added in ES5 (not supported under IE9).

/****js Native traversal****/

//for loop traversal array

for ( var  i=0;i<arrTmp.length;i++){

     console.log(i+ ": " +arrTmp[i])

}



//For in traverses the object attribute, and i refers to the attribute name

for ( var  i  in  objTmp){

     console.log(i+ ": " +objTmp[i])

}



//forEach traverses the array. The three parameters are array element, index and array itself

arrTmp.forEach( function (value,index,array){

     console.log(value+ "," +index+ "," +array[index])

})

 

    2. The for in loop is designed to traverse objects. In fact, for in can also be used to traverse arrays, but the defined index i is of string type. If the array has an enumerable method, it will also be traversed by for in, for example:

//For in traversal array
for ( var  i  in  arrTmp){
     console.log(i+ ": " +arrTmp[i])
}
//For in will traverse the properties of the array
arrTmp.name= "myTest" ;
for ( var  i  in  arrTmp){
     console.log(i+ ":" +arrTmp[i])
}
//Output 0: value1 1: Value2 2: value3 Name: mytest

    3. for loop and for in can correctly respond to break, continue and return statements, but forEach cannot.

//Only value1 and Value2 will be output
for ( var  i=0;i<arrTmp.length;i++){
     console.log(i+ ": " +arrTmp[i]);
     if (i==1){
         break ;
     }
}
 
//value1 value2 value3 will be output
arrTmp.forEach( function (value){
     console.log(value+);
     if (value==1){
         return ;
     }
})

4. In ES6, the for of traversal method is added. It is designed to traverse a variety of class array collections, such as DOM NodeList objects, Map and Set objects, and even strings. The official statement is:

for...of statementcreates an iteration loop on iteratable objects (including Array, Map, Set, String, TypedArray, arguments objects, etc.), and calls a custom iteration hook with execution statement for the attribute value of each different attribute

// For of traverses the array without index, i is the array element
for ( let  i of arrTmp){
     console.log(i)
}
//Output "value1" "value2" "value3"
 
// For of traversal Map object
let  iterable =  new  Map([[ "a" , 1], [ "b" , 2], [ "c" , 3]]);
for  ( let  [key, value] of iterable) {
   console.log(value);
}
//Output 1 2 3
 
// For of traversal string
let  iterable =  "china China" ;
for  ( let  value of iterable) {
   console.log(value);
}
//Output "c" "h" "i" "n" "a" "China" "country"

 

5. The above methods focus on the attribute values of array elements or objects. If you simply want to get the attribute name of an object, js has a native Object.keys() method (incompatible with IE in earlier versions), which returns an array composed of enumerable attribute names of the object:

/****Object.keys()Returns an array of key names****/
//Array type
let  arr = [ "a" ,  "b" ,  "c" ];
console.log(Object.keys(arr));
// (3) ['0', '1', '2']
 
// Class array object
let  anObj = { 100:  'a' , 2:  'b' , 7:  'c'  };
console.log(Object.keys(anObj));
// (3) ['2', '7', '100']
 
//General object
let  xyz = {z:  "zzz" , x:  "xxx" , y:  "yyy" };
console.log(Object.keys(xyz));
// (3) ["z", "x", "y"]

Suggested usage of javascript native traversal method:

  • Traversing an array with a for loop
  • Traversing objects with for in
  • Traversing class array objects with for of (ES6)
  • Get the collection of object attribute names with Object.keys()

What is the difference between a for... of loop and a for... in loop  

for... in loop, which actually traverses the property name of the object.

An Array is actually an object, and the index of each element of it is regarded as an attribute.

When we manually add additional attributes to the Array object, the for... in loop will bring unexpected effects:

When traversing an array, for in takes the array index as the key value, such as the key of array 0, 1, 2, 3, 4, 5; When we write:

var arr=[1,2,3,4,5,6];

arr.value='val';

//When traversing with for in

for(var i in arr){

console.log(i+' '+arr[i]);//At this time, i is the key value, not the array index

}

//output

0 1
1 2
2 3
3 4
4 5
5 6

value val

Then execute, and a problem occurs:


arr;//Output [1, 2, 3, 4, 5, 6]


//When using console.log(arr), this

console.log(arr);//Output [1, 2, 3, 4, 5, 6, value: "val"]


//alert(arr)

alert(arr);//Output [1, 2, 3, 4, 5, 6]

When we use for of:

var arr=[1,2,3,4,5,6];

arr.value='val';

//When traversing with for in

for(var v of arr){

    console.log(v);//v is the item of the array

}

//output

1
2
3
4
5
6

Directly traverse the value to eliminate the influence of subscript index when using for in

$. each of jQuery

    jQuery's traversal method is usually used to traverse DOM elements. The $. each() method is used for arrays and objects. It accepts three parameters, respectively referring to the array index / element / array itself (compared with forEach, the first and second parameters are exactly the opposite. Don't remember wrong.):

/****$.each()Traversing objects and arrays****/
$.each(arrTmp, function (index,value,array){
     console.log(index+ ": " +value)
});
 
$.each(objTmp, function (key,value){
     console.log(key+ ": " +value)
});

map

Map here does not mean "map", but "mapping". [].map(); The basic usage is similar to the forEach method:

array.map(callback,[ thisObject]);

The callback parameters are similar:

[].map(function(value, index, array) {  
         // ...
   });

The function of the map method is not difficult to understand. The "mapping" means that the original array is "mapped" to the corresponding new array. The following example is the square of the numerical term:

var data=[1,3,4]
var Squares=data.map(function(val,index,arr){
    console.log(arr[index]==val);  // ==> true
    return 
    val*val           
})
console.log(Squares);// ==> [1, 9, 16]

Posted by 9mm on Mon, 06 Dec 2021 23:31:41 -0800