JS中reduce方法

定義和用法

  1. reduce() 方法接收一個函數做爲累加器,數組中的每一個值(從左到右)開始縮減,最終計算爲一個值。
  2. reduce() 能夠做爲一個高階函數,用於函數的 compose
  3. reduce() 對於空數組是不會執行回調函數的

瀏覽器支持

支持谷歌、火狐、ie9以上等主流瀏覽器數組

語法

array.reduce(function(prev, current, currentIndex, arr), initialValue)
  1. prev:函數傳進來的初始值或上一次回調的返回值
  2. current:數組中當前處理的元素值
  3. currentIndex:當前元素索引
  4. arr:當前元素所屬的數組自己
  5. initialValue:傳給函數的初始值

初始值爲數值:瀏覽器

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
       const sum = arr.reduce(function (prev, current) {
         return prev+current
       }, 0)
       console.log(sum) //55

reduce根據函數傳進來的初始值,不斷回調疊加最終算出數組的和函數

初始值爲對象:code

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
       const sum = arr.reduce(function (prev, current) {
         prev.count = prev.count+current
         return prev
       }, {count: 0})
       console.log(sum) //{count: 55}

若是初始值爲對象的話,返回的也是一個對象對象

初始值爲數組:索引

const str = 'hello'
      const newstr = str.split('').reduce(function (prev, current) {
         const obj = {};
         obj[current] = current;
         prev.push(obj)
         return prev;
      }, [])
      console.log(newstr)

結果爲:回調函數

[{
        h: 'h'
      },{
        e: 'e'
      },{
        l: 'l'
      },{
        l: 'l'
      },{
        o: 'o'
      }]

若是初始值爲數組,則返回的也是數組it

reduce應用:io

{
      function func1(a) {
        return a*10;
      }

      function func2(b) {
        return b*2
      }

      const test1 = func1(2)
      const test2 = func2(test1)
      console.log(test2) //40
    }

這裏咱們須要先執行方法func1再根據func1返回的值,而後執行方法func2,咱們有時候會碰到不止兩個方法一塊兒,若是是多個呢,這個時候就要用到reduce來處理了console

function func1(a) {
        return a*10;
      }

      function func2(b) {
        return b*2
      }

      function func3(c) {
        return c/2;
      }
      const compose = (...func) => (...init) => {
          if(func.length >= 2){
            return func.reduce((prev, curr)=>{
               prev = curr(prev)
               return prev;
            }, ...init)
          }
          return func(...init);
      }

      const a1 = compose(func1,func2)(2);
      console.log(a1) //40
      const a2 = compose(func1,func2,func3)(2);
      console.log(a2) //20
相關文章
相關標籤/搜索