.reduce
语法
.reduce(function(previousValue, currentValue, currentIndex, array){ /* 代码 return xx */}, initialValue)
有返回值,不会改变当前数组
参数
function(previousValue, currentValue, currentIndex, array):返回值赋给previousValue
previousValue(必需):previousValue初始值的等于initialValue
currentValue(必需):当前遍历的值
currentIndex(可选):当前遍历的值的索引
array(可选):当前数组
initialValue(可选):默认为是array索引值为1的值
例子
数组累加
const intArr = [5, 5, 8, 9, 7, 6]
const add = intArr.reduce((pre, cur, curIndex, array) => {
// console.log("输出pre, cur, curIndex, array:",pre, cur, curIndex, array)
return pre + cur
})
console.log("add:", add)
/**
* 数组累加
* @returns 数组累加
*/
Array.prototype.sum = function(){
return this.reduce((pre, cur) => {
//console.log("输出pre, cur:",pre, cur)
return pre + cur
})
}
console.log("sum:",intArr.sum())
const strArr = ["hello", ",", "world"]
console.log("sum:",strArr.sum())
二维数组转换成一维数组
const twoDimensionalMatrix = [[5, 5, 8, 9, 7, 6], [5, 5, 8, 9, 7, 6], [5, 5, 8, 9, 7, 6]]
const oneDimensionalMatrix = twoDimensionalMatrix.reduce((pre, cur, curIndex, array) => {
// console.log("输出pre, cur, curIndex, array:",pre, cur, curIndex, array)
pre.push(...cur)
return pre
}, [])
console.log("oneDimensionalMatrix:", oneDimensionalMatrix)
/**
* 二维数组转换成一维数组
* @returns 二维数组转换成一维数组
*/
Array.prototype.toOneDimensionalMatrix = function(){
return this.reduce((pre, cur) => {
//console.log("输出pre, cur:",pre, cur)
pre.push(...cur)
return pre
}, [])
}
console.log("toOneDimensionalMatrix:", twoDimensionalMatrix.toOneDimensionalMatrix())
数组去重
const arr = [1, 2, 3, 7, 2, 3, 5, 6, 9, 7, 2, 3, 5, 8]
const arrSet = arr.reduce((pre, cur, curIndex, array) => {
// console.log("输出pre, cur, curIndex, array:",pre, cur, curIndex, array)
if(pre.indexOf(cur) === -1){
pre.push(cur)
}
return pre
}, [])
console.log("arrSet:", arrSet)
/**
* 二维数组转换成一维数组
* @returns 二维数组转换成一维数组
*/
Array.prototype.toSet = function(){
return this.reduce((pre, cur) => {
//console.log("输出pre, cur:",pre, cur)
if(pre.indexOf(cur) === -1){
pre.push(cur)
}
return pre
}, [])
}
console.log("toSet:", arr.toSet())