站長資訊網
        最全最豐富的資訊網站

        深入解析JS中數組reduce方法(附代碼)

        之前的文章《淺談Vue中key取值影響過渡效果和動畫效果(代碼詳解)》中,給大家了解一下Vue中key取值影響過渡效果和動畫效果。下面本篇給大家了解一下JS中數組reduce方法,有一定的參考價值,有需要的朋友可以參考一下。

        深入解析JS中數組reduce方法(附代碼)

        含義

        reduce()方法對累加器和數組中的每個元素(從左到右)應用一個函數,將其減少為單個值。

        語法

        arr.reduce(callback[, initialValue])

        參數

        callback執行數組中每個值的函數,包含四個參數:accumulator累加器累加回調的返回值;它是上一次調用回調時返回的累積值,或initialValue(如下所示)。

        currentValue

        數組中正在處理的元素。currentIndex可選

        數組中正在處理的當前元素的索引。 如果提供了initialValue,則索引號為 0,否則為索引為 1。array可選

        調用reduce的數組initialValue可選

        用作第一個調用callback的第一個參數的值。如果沒有提供初始值,則將使用數組中的第一個元素。在沒有初始值的空數組上調用reduce將報錯。Link to section返回值函數累計處理的結果

        例子

        求數組[1,2,3,4,5]里所有值的和

        // 1 遍歷求和 let count = 0; let arr = [1, 2, 3, 4, 5]; for (let i = 0; i < arr.length; i++) {   count += arr[i]; } console.log(count); // output 15  // 2 eval let count = eval([1, 2, 3, 4, 5].join("+")); console.log(count); // output 15  // 3 reduce let count = [1, 2, 3, 4, 5].reduce((a, b) => a + b); console.log(count); // output 15

        將二維數組轉化為一維

        var flattened = [   [0, 1],   [2, 3],   [4, 5], ].reduce((acc, cur) => acc.concat(cur), []);

        計算數組中每個元素出現的次數

        var names = ["Alice", "Bob", "Tiff", "Bruce", "Alice"];  var countedNames = names.reduce(function (allNames, name) {   if (name in allNames) {     allNames[name]++;   } else {     allNames[name] = 1;   }   return allNames; }, {}); // countedNames is: // { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

        使用擴展運算符和initialValue綁定包含在對象數組中的數組

        // friends - an array of objects // where object field "books" - list of favorite books var friends = [   {     name: "Anna",     books: ["Bible", "Harry Potter"],     age: 21,   },   {     name: "Bob",     books: ["War and peace", "Romeo and Juliet"],     age: 26,   },   {     name: "Alice",     books: ["The Lord of the Rings", "The Shining"],     age: 18,   }, ];  // allbooks - list which will contain all friends' books + // additional list contained in initialValue var allbooks = friends.reduce(   function (prev, curr) {     return [...prev, ...curr.books];   },   ["Alphabet"] );  // allbooks = [ //   'Alphabet', 'Bible', 'Harry Potter', 'War and peace', //   'Romeo and Juliet', 'The Lord of the Rings', //   'The Shining' // ]

        數組去重

        let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4]; let result = arr.sort().reduce((init, current) => {   if (init.length === 0 || init[init.length - 1] !== current) {     init.push(current);   }   return init; }, []); console.log(result); //[1,2,3,4,5]

        數組取最大值和最小值

        let data = [1, 4, 2, 2, 4, 5, 6, 7, 8, 8, 9, 10]; //取最小值 let min = data.reduce((x, y) => (x > y ? y : x)); //取最大值 let max = data.reduce((x, y) => (x > y ? x : y));

        ES5的實現

        if (!Array.prototype.reduce) {   Object.defineProperty(Array.prototype, "reduce", {     value: function (callback /*, initialValue*/) {       if (this === null) {         throw new TypeError(           "Array.prototype.reduce " + "called on null or undefined"         );       }       if (typeof callback !== "function") {         throw new TypeError(callback + " is not a function");       }        // 1. Let O be ? ToObject(this value).       var o = Object(this);        // 2. Let len be ? ToLength(? Get(O, "length")).       var len = o.length >>> 0;       // >>表示是帶符號的右移:按照二進制把數字右移指定數位,高位如符號位為正補零,符號位負補一,低位直接移除       //  >>>表示無符號的右移:按照二進制把數字右移指定數位,高位直接補零,低位移除。        // Steps 3, 4, 5, 6, 7       var k = 0;       var value;        if (arguments.length >= 2) {         value = arguments[1];       } else {         while (k < len && !(k in o)) {           k++;         }          // 3. 長度為0 且初始值不存在 拋出異常         if (k >= len) {           throw new TypeError(             "Reduce of empty array " + "with no initial value"           );         }         value = o[k++];       }        // 8. Repeat, while k < len       while (k < len) {         // a. Let Pk be ! ToString(k).         // b. Let kPresent be ? HasProperty(O, Pk).         // c. If kPresent is true, then         //    i.  Let kValue be ? Get(O, Pk).         //    ii. Let accumulator be ? Call(         //          callbackfn, undefined,         //          ? accumulator, kValue, k, O ?).         if (k in o) {           value = callback(value, o[k], k, o);         }          // d. Increase k by 1.         k++;       }        // 9. Return accumulator.       return value;     },   }); }

        推薦學習:JavaScript視頻教程

        贊(0)
        分享到: 更多 (0)
        網站地圖   滬ICP備18035694號-2    滬公網安備31011702889846號
        主站蜘蛛池模板: 97精品伊人久久大香线蕉app| 国产精品一在线观看| 国产精品无码AV一区二区三区| 国产精品亚洲美女久久久| AV无码精品一区二区三区| 亚洲精品色午夜无码专区日韩| 国产亚洲精品线观看动态图| 国产AV无码专区亚洲精品 | 久久99精品久久只有精品| 国内精品免费久久影院| 最新国产精品亚洲| 国产一区二区精品| 国产精品露脸国语对白| 亚洲?V乱码久久精品蜜桃| 国产精品免费视频观看拍拍| 久久精品国产亚洲麻豆| 国产精品久久一区二区三区 | 国产精品欧美久久久久无广告| 国产成人精品久久一区二区三区| 日韩精品久久久肉伦网站| 尤物yw午夜国产精品视频| 日本精品一区二区三区四区| 国産精品久久久久久久| 99热热久久这里只有精品68 | 精品人妻少妇一区二区| 国产成人综合久久精品尤物| 亚洲精品成人av在线| 四虎在线精品视频一二区| 国产短视频精品一区二区三区| 国产精品天干天干综合网| 久久ww精品w免费人成| 精品爆乳一区二区三区无码av| 日韩精品少妇无码受不了| 人妻少妇精品视频一区二区三区| 一本一本久久aa综合精品| 亚洲精品V欧洲精品V日韩精品 | 国产精品熟女一区二区| 精品久久久久久亚洲精品| 国产在线精品一区二区中文| 国产成人精品手机在线观看| 成人午夜视频精品一区|