Several common array traversal methods in Js

array traversal

1. forEach()

arr.forEach(callback(currentValue [, index [, array]])[, thisArg])
  • callback

    A function to be executed for each element in the array, which takes one to three arguments:

    currentValueThe current element in the array being processed.

    indexThe index of the current element in the optional array being processed.

    arrayThe optional array itself.

  • thisArgoptional

    Optional parameter. callbackUsed as the value of when the callback function is executed this.

example
 let arr = [1,2,3,4,5]
        arr.forEach(function(value,index){
    
    
            arr[index] +=1;
        })
        console.log(arr); //输出 [2,3,4,5,6]
		

2. map()

Create a new array, each element of which calls each element in the array to execute the provided function;

  • The difference between forEach and map

    The forEach() method will not return the execution result, but undefined.

    In other words, forEach() will modify the original array. The map() method will get a new array and return it.

3. some()

Traverse the array, as long as more than one element meets the condition, return true, otherwise return false, and exit the loop.

arr.some(callback(element[, index[, array]])[, thisArg])

4. every()

Iterates through the array and returns true if each element satisfies the condition, otherwise returns false.

5. for…in

Mainly used to traverse objects, the format in for(): key represents the keyfor(key in obj){} of each key-value pair of obj object

6. for…of

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

        for (let a in arr) {
    
    
          console.log(a); // 0 1 2 3
        }

        for (let a of arr) {
    
    
          console.log(a); // a b c d
        }

The above code shows that the **for...in loop reads the key name, and the for...of loop reads the key value. **If you want to get the index of the array through the for...of loop, you can use the entries method and keys method of the array instance

The for...in loop has several disadvantages
  ① The key names of the array are numbers, but the for...in loop uses strings as the key names "0", "1", "2" and so on.
  ②The for...in loop not only traverses the numeric key names, but also traverses other keys manually added, even including keys on the prototype chain.
  ③In some cases, the for...in loop will traverse the key names in any order.
  The for...in loop is primarily designed for traversing objects , not for traversing arrays.

The for...of loop
  has the same concise syntax as for...in, but without the disadvantages of for...in.
  Unlike the forEach method, it can be used with break, continue, and return.
  Provides a unified operation interface for traversing all data structures

Guess you like

Origin blog.csdn.net/m0_46893049/article/details/125757802