之前的文章《淺談Vue中key取值影響過(guò)渡效果和動(dòng)畫(huà)效果(代碼詳解)》中,給大家了解一下Vue中key取值影響過(guò)渡效果和動(dòng)畫(huà)效果。下面本篇給大家了解一下JS中數(shù)組reduce方法,有一定的參考價(jià)值,有需要的朋友可以參考一下。
含義
reduce()
方法對(duì)累加器和數(shù)組中的每個(gè)元素(從左到右)應(yīng)用一個(gè)函數(shù),將其減少為單個(gè)值。
語(yǔ)法
arr.reduce(callback[, initialValue])
參數(shù)
callback
執(zhí)行數(shù)組中每個(gè)值的函數(shù),包含四個(gè)參數(shù):accumulator
累加器累加回調(diào)的返回值;它是上一次調(diào)用回調(diào)時(shí)返回的累積值,或initialValue
(如下所示)。
currentValue
數(shù)組中正在處理的元素。currentIndex
可選
數(shù)組中正在處理的當(dāng)前元素的索引。 如果提供了initialValue
,則索引號(hào)為 0
,否則為索引為 1
。array可選
調(diào)用reduce
的數(shù)組initialValue
可選
用作第一個(gè)調(diào)用callback
的第一個(gè)參數(shù)的值。如果沒(méi)有提供初始值,則將使用數(shù)組中的第一個(gè)元素。在沒(méi)有初始值的空數(shù)組上調(diào)用reduce
將報(bào)錯(cuò)。Link to section
返回值函數(shù)累計(jì)處理的結(jié)果
例子
求數(shù)組[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
將二維數(shù)組轉(zhuǎn)化為一維
var flattened = [ [0, 1], [2, 3], [4, 5], ].reduce((acc, cur) => acc.concat(cur), []);
計(jì)算數(shù)組中每個(gè)元素出現(xiàn)的次數(shù)
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 }
使用擴(kuò)展運(yùn)算符和initialValue
綁定包含在對(duì)象數(shù)組中的數(shù)組
// 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' // ]
數(shù)組去重
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]
數(shù)組取最大值和最小值
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的實(shí)現(xiàn)
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; // >>表示是帶符號(hào)的右移:按照二進(jìn)制把數(shù)字右移指定數(shù)位,高位如符號(hào)位為正補(bǔ)零,符號(hào)位負(fù)補(bǔ)一,低位直接移除 // >>>表示無(wú)符號(hào)的右移:按照二進(jìn)制把數(shù)字右移指定數(shù)位,高位直接補(bǔ)零,低位移除。 // 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. 長(zhǎng)度為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; }, }); }
推薦學(xué)習(xí):JavaScript視頻教程