一、什么是 reduce() ?
reduce() 方法對陣列中的每個元素執行一個升序執行的 reducer 函式,并將結果匯總為單個回傳值
const array1 = [1, 2, 3, 4]; const reducer = (accumulator, currentValue) => accumulator + currentValue; // 1 + 2 + 3 + 4 console.log(array1.reduce(reducer)); // 輸出: 10 // 5 + 1 + 2 + 3 + 4 console.log(array1.reduce(reducer, 5)); // 輸出: 15
二、陣列中 reduce 方法的引數
1、第一個引數:reducer 函式
其中,reducer 函式又有四個引數:
- Accumulator (acc) (累計器)
- Current Value (cur) (當前值)
- Current Index (idx) (當前索引)
- Source Array (src) (源陣列)
2、第二個引數(可選):initialValue
代表傳遞給函式的初始值
// 不傳第二個引數的情況 var numbers = [1, 2, 3, 4] function myFunction(item) { let result = numbers.reduce(function (total, currentValue, currentIndex, arr) { console.log(total, currentValue, currentIndex, arr) return total + currentValue }) return result } myFunction(numbers)
輸出:

可以看到如果不傳第二個引數 initialValue,則函式的第一次執行會將陣列中的第一個元素作為 total 引數回傳,一共執行3次
下面是傳遞第二個引數的情況:
// 不傳第二個引數的情況 var numbers = [1, 2, 3, 4] function myFunction(item) { let result = numbers.reduce(function (total, currentValue, currentIndex, arr) { console.log(total, currentValue, currentIndex, arr) return total + currentValue }, 10) return result } myFunction(numbers)
輸出:
如果傳了第二個引數 initialValue,那么第一次執行的時候 total 的值就是傳遞的引數值,然后再依次遍歷陣列中的元素,執行4次
總結:如果不傳第二引數 initialValue,那么相當于函式從陣列第二個值開始,并且將第一個值最為第一次執行的回傳值,如果傳了第二個引數 initialValue,那么函式從陣列的第一個值開始,并且將引數 initialValue 作為函式第一次執行的回傳值
三、應用場景
1、陣列里所有值的和
var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) { return accumulator + currentValue; }, 0); // 和為 6
2、累加物件陣列里的值
var initialValue = https://www.cnblogs.com/Leophen/p/0; var sum = [{x: 1}, {x:2}, {x:3}].reduce(function (accumulator, currentValue) { return accumulator + currentValue.x; },initialValue) console.log(sum) // logs 6
3、將二維陣列轉化為一維
var flattened = [[0, 1], [2, 3], [4, 5]].reduce( function(a, b) { return a.concat(b); }, [] ); // flattened is [0, 1, 2, 3, 4, 5]
4、計算陣列中每個元素出現的次數
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 }
5、陣列去重
var myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']; var myOrderedArray = myArray.reduce(function (accumulator, currentValue) { if (accumulator.indexOf(currentValue) === -1) { accumulator.push(currentValue); } return accumulator }, []) console.log(myOrderedArray);
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]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/141452.html
標籤:JavaScript
下一篇:js精準計算
