JS object-array processing method reduce method

 reduce() method

1. This method receives a function as an accumulator, and each value in the array (from left to right) is reduced and finally calculated as a value;

2. This method can be used as a higher-order function to compose the function

note

This method will not execute the callback function for empty arrays.

grammar

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
parameter description
function(total,currentValue,index,arr)

Required, used to execute the function of each array element

parameter description
total Required. Initial value, or return value after calculation
currentValue Required, current element
currentIndex Optional. The index of the current element
arr Optional. The array object to which the current element belongs
initialValue Optional, the initial value passed to the function

 

 

 

 

 

 

 

 

 

If the initial value is not set, the loop will start at index zero.

Practical application (1)

官方案例-累加计算

function getSum(total, num) {
  
    
     return total + num;

}
[65, 44, 12, 4].reduce(getSum)

//没有设置初始值,循环从数组索引为零开始执行。

Practical application (two)

 //判断数组是否连续
  let a1rr = [3, 4, 4, 6, 7, 8, 9, 10, 11];
  function getContinueFun2(arr) {
           let ress = arr.reduce((flag, cur, ind, arr) => {
            arr[ind + 1] - cur == 1 ? flag++ : ''
              return flag;
       }, 0);
      return ress == arr.length - 1
  }
  getContinueFun2(a1rr)

 

Practical application (3)

//每个值出现次数都为一。如果是返回true,否则返回false。

  function getUniNum(arr) {
           let obj = arr.reduce((obj, curr, i, arr) => {
                obj[curr] ?  obj[curr]++ : obj[curr] = 1;
                return obj
            }, {});
            return Object.values(obj).length === arr.length
  }
  getUniNum([1,'name',2,4,3,'name'])

Novice, welcome to discuss.

Guess you like

Origin blog.csdn.net/qq_40010841/article/details/113882693