js traversal method summary

1. Ordinary for loop

语法:for(j = 0,len=arr.length; j < len; j++) {....}

illustrate:

1. Use temporary variables to cache the length to avoid repeatedly obtaining the length of the array. The optimization effect will be more obvious when the array is large.

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

 

2、forEach()

语法:arr.forEach(function(value,index,array){...}

illustrate:

1. No return value

2. Parameters: the current item in the value array, index the index of the current item, the original array of array

3. In theory, this method has no return value. It just traverses each item in the array and does not modify the original array; but you can modify the original array by yourself through the index of the array;

 

3、map()

语法:arr[].map(function(value,index,array){...}

illustrate:

1. There is a return value, which returns a new array, each item in it is the value returned in the anonymous function

2. Parameters: the current item in the value array, index the index of the current item, the original array of array;

3. Difference: The callback function of map supports return return value; what is returned is equivalent to changing this item in the array to what

(It does not affect the original array, but it is equivalent to cloning a copy of the original array, and changing the corresponding item in the cloned array);

 

4. for...in loop

Syntax: for(var key in obj){...}

illustrate:

1. Unordered loop is the least efficient for traversing arrays, and is often used to traverse objects

(Array indices are just enum properties with integer names, and are the same as generic object properties. There is no guarantee that for...in will return indices in any particular order)

2. Traverse only self and inherited enumerable properties

 

5. for...of loop (ES6)

Syntax: for(let value of iterator){...}

illustrate:

1. It is used for loop iterator (Iterator), the array natively has the Iterator interface, so it can also be traversed with for...of

2. In-order traversal

3, Set, Map, Generator can also use this traversal

4. Ordinary objects can be traversed directly using for...of. You can use Object.keys() to take out the enumerable properties of the object and combine them into an array, and then traverse the key-value array

for(let key of Object.keys(obj)){

     let value = obj[key]

}

5. Can be used in conjunction with break, continue, and return

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324981500&siteId=291194637