“This is the sixth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

This is the last installment in our series on common methods for arrays, and we’ll cover methods for array traversal.

Array traversal method

forEach()

Definition: The forEach() method performs a given function once on each element of the array that has a valid value. Those that have been deleted or not initialized are skipped, always returning undefined.

Array.prototype. ForEach (currentValue,index, Array),thisArg)

Parameters:

  1. Callback (Mandatory) : A function that is executed once for each element of the array with valid values and takes one to three arguments.
  2. CurrentValue (Mandatory) : The current element in the array being processed.
  3. Index (Optional) : Index of the current element being processed in the array.
  4. Array (Optional) : Array being operated on.
  5. ThisArg (optional) : When executedcallbackWhen used asthisThe value of the.

Use:

let arr = [1.2.3.4.5]
let callback = function(currentValue,index,array) {
    if(currentValue == 3)
        return;
    if(currentValue == 4)
        throw Error('Throwing an exception can break/break the loop')
    console.log(currentValue,index,array)
}
arr.forEach(callback)
Copy the code

Note: You must throw an exception to break/break the loop. Using return can only exit this callback for the next callback.

map()

Definition: The map() method creates a new array. The result is the return value of each element in the array after a call to the callback function.

Array.prototype. Map (callback(currentValue,index, Array),thisArg)

Parameters:

  1. Callback (Mandatory) : A function that is executed once for each element of the array with valid values and takes one to three arguments.
  2. CurrentValue (Mandatory) : The current element in the array being processed.
  3. Index (Optional) : Index of the current element being processed in the array.
  4. Array (Optional) : Array being operated on.
  5. ThisArg (optional) : When executedcallbackWhen used asthisThe value of the.

Use:

let arr = [1.2.3.4.5]
let resArr = arr.map(item= > item * 2)
console.log(arr)        // [1, 2, 3, empty, 4, 5]
console.log(resArr)     // [2, 4, 6, empty, 8, 10]
Copy the code

filter()

Definition: The filter() method creates a new array containing all the elements of the test implemented by the provided function.

Array.prototype.filter(currentValue,index, Array) thisArg

Parameters: same as above.

Use:

let arr = [1.2.3.4.5]
let filterArr = arr.filter(item= > item >= 3)
console.log(filterArr)   / / [3, 4, 5]
Copy the code

every()

Definition: The every() method tests whether all elements in an array pass the test of a given function. It returns a Boolean value.

Array.prototype. Every (callback(currentValue,index, Array),thisArg)

Parameters: same as above.

Use:

let arr = [1.2.3.4.5]
let everyRes = arr.every(item= > item > 0)
let everyRes1 = arr.every(item= > {
    console.log(item);
    return item > 2
})                                  / / 1
                                    // If one of them is not satisfied, return false
console.log(everyRes,everyRes1)     // true false
Copy the code

some()

Definition: The some() method tests that at least one element in an array passes the provided function test. It returns a Boolean value.

Array.prototype. Some (currentValue,index, Array),thisArg)

Parameters: same as above.

Use:

let arr = [1.2.3.4.5]
let someRes =arr.some(item= > item < 0)
let someRes1 = arr.some(item= > {
    console.log(item)
    return item > 0
})                               / / 1
                                 // If one of them is true, return true
console.log(someRes,someRes1)    // false true
Copy the code

reduce()

Definition: The reduce() method performs a custom Reducer function (executed in ascending order) on each element in the array and summarizes its results into a single return value.

Reduce (Reducer (pre,cur,index, Array)

Parameters:

  1. Reducer (Mandatory) : A user-defined function with two to four parameters.
  2. Pre (Mandatory) : Cumulative value returned by the last callback, orinitialValue.
  3. Cur (Mandatory) : The value currently being processed in the array.
  4. Index (Optional) : Index of the value currently being processed in the array.
  5. Array (Optional) : The original array from which the method is called.
  6. InitialValue (Optional) : As the first callreducerThe value of the first argument to the function.

Note: The first time the callback is executed, if initialValue is provided, pre equals it and cur is the first element of the array. If not, pre takes the value of the first element in the array, and cur is the second element in the array.

Use:

let arr = [1.2.3.4.5]
arr.reduce((pre,cur,index,array) = > {
    console.log(pre,cur,index,arr)
})
console.log('-- division line --')

// Use reduce to sum
let sum = arr.reduce((pre,cur) = > {
    console.log(pre,cur)
    return pre + cur
})
console.log('sum = ',sum)

// Use reduce to calculate the number of repetitions
let nums = [1.1.2.3.4.4.4.5.6.7.8.8.8.8.8.8.9]
let res = nums.reduce((pre,cur) = >{
    if(! pre[cur]) pre[cur] =1
    else pre[cur] ++
    return pre
},{})
console.log(res)
Copy the code

Think about it, why is undefined in the red box?

Because in our first code, the callback function did not return a value, so the second callback will always be undefined.

reduceRight()

There is no difference from reduce() except that the order is from right to left.

find() & findIndex()

Definition: The find() method returns the value of the first element in the array that satisfies the provided test function. Otherwise return undefined.

The findIndex() method returns the index of the first element in the array that satisfies the provided test function. Otherwise -1 is returned.

Both recognize NaN.

Grammar: Array. The prototype. The find/findIndex (callback (currentValue, index, Array), thisArg)

Parameters:

  1. Callback (Mandatory) : A function that is executed once for each element of the array with valid values and takes one to three arguments.
  2. CurrentValue (Mandatory) : The current element in the array being processed.
  3. Index (Optional) : Index of the current element being processed in the array.
  4. Array (Optional) : Array being operated on.
  5. ThisArg (optional) : When executedcallbackWhen used asthisThe value of the.

Use:

let arr = [1.2.NaN, -1, -3.NaN.4]
let item = arr.find(item= > item < 0)
let index = arr.findIndex(item= > Object.is(NaN,item))
console.log(item,index)      / / - 1. 2
Copy the code

conclusion

That’s it for array traversal.

Welcome to point out any mistakes!