關於數組的reduce的妙用之處

在前端開發過程、或者面試過程當中,別人問你數組經常使用的操做,你也許馬上立刻回答for循環、forEachfor..ofmapsome......reduce等方法。我相信前端開發的小夥伴,10我的中有8個對reduce僅僅是停留在數據累加上, 下面本人介紹一些reduce函數的妙用之處。前端

1、回顧下reduce函數的參數問題

  • 一、reduce函數面試

    Array.prototype.reduce(function(previousVal, currentVal, index, _this) {
      // 函數體
    }, initVal);
    複製代碼
  • 二、理解上面的函數後端

    • 1.reduce函數也是對數組迭代的過程
    • 2.第一次循環的時候,previousVal==initVal
    • 3.從第二次開始,previousVal==reducer函數中的返回值了
    • 四、index表示當前數組的序列化
    • 五、_this表示當前的數組

2、本身手動實現一個reduce函數

  • 一、本身擴展數組的方法數組

    Array.prototype.myReduce = function(fn, initVal) {
      if (Object.prototype.toString.call(this) != '[object Array]') {
        throw new Error('當前是數組的方法,不能使用到別的上面');
      }
      let total;
      if (initVal != undefined) {
        total = initVal;
      } else {
        total = this[0];
      }
      if (initVal === undefined) {
        for (let i = 1; i < this.length; i++) {
          total = fn(total, this[i], i, this);
        }
      } else {
        for (let [index, val] of this.entries()) {
          total = fn(total, val, index, this);
        }
      }
      return total;
    };
    複製代碼

1、數據累加

  • 一、數據原函數

    let ary1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    複製代碼
  • 二、數據疊加工具

    const result = ary1.reduce((pre, cur) => pre + cur);
    console.log(result);
    複製代碼

2、將數組轉換爲對象

  • 一、實現代碼ui

    const userList = [
      {
        id: 1,
        username: 'john',
        sex: 1,
        email: 'john@163.com'
      },
      {
        id: 2,
        username: 'jerry',
        sex: 1,
        email: 'jerry@163.com'
      },
      {
        id: 3,
        username: 'nancy',
        sex: 0,
        email: ''
      }
    ];
    
    let result = userList.reduce((pre, current) => {
      return {...pre, [current.id]: current};
    }, {});
    
    console.log(result);
    複製代碼

3、將大數組轉換成小數組

  • 一、實現代碼this

    const fileLines = [
      'Inspector Algar,Inspector Bardle,Mr. Barker,Inspector Barton',
      'Inspector Baynes,Inspector Bradstreet,Inspector Sam Brown',
      'Monsieur Dubugue,Birdy Edwards,Inspector Forbes,Inspector Forrester',
      'Inspector Gregory,Inspector Tobias Gregson,Inspector Hill',
      'Inspector Stanley Hopkins,Inspector Athelney Jones'
    ];
    
    let result = fileLines.reduce((pre, current) => {
      return pre.concat(current.split(/,/g));
    }, []);
    
    console.log(result);
    複製代碼

4、將數組展開

  • 一、實現代碼spa

    const arr = ["今每天氣不錯", "", "早上好"];
    
    const arr2 = arr.reduce((pre, cur) => {
      return pre.concat(cur.split(''));
    }, []);
    console.log(arr2);
    複製代碼

5、求數組的最大值與最小值

  • 一、實現代碼.net

    const readings = [0.3, 1.2, 3.4, 0.2, 3.2, 5.5, 0.4];
    
    let minValue = readings.reduce((x,y) => Math.min(x,y));
    console.log(minValue);
    let maxValue = readings.reduce((x,y) => Math.max(x,y));
    console.log(maxValue);
    複製代碼

6、使用reduce寫一個工具方法,用來提取對象中的數據

  • 一、後端返回的一個對象

    let obj1 = {
      "result": {
        "report": {
          "contactInfo": {
            "callsNumber": 0,
            "contactsNumber": 0,
            "emergencyContactHasOverdue": "No",
            "sameLiainson": {
              "isSame": "Yes",
              "accounts": "aa"
            }
          }
        }
      }
    };
    複製代碼
  • 二、使用reduce的工具方法

    const objectGetVal = (obj, expr) => {
      if (!Object.is(Object.prototype.toString.call(obj), '[object Object]')) {
        throw new Error(`${obj}不是對象`);
      }
      if (!Object.is(Object.prototype.toString.call(expr), '[object String]')) {
        throw new Error(`${expr}必須是字符串`);
      }
      return expr.split('.').reduce((prev, next) => {
        if (prev) {
          return prev[next]
        } else {
          return undefined;
        }
      }, obj)
    };
    console.log(objectGetVal(obj1, 'result.report.contactInfo.emergencyContactHasOverdue'));
    console.log(objectGetVal(obj1, 'result.report.emergencyContactHasOverdue'));
    // 輸出結果
    // No
    // undefined
    複製代碼

7、使用reduce生成樹型菜單參考

相關文章
相關標籤/搜索