文章目录
一、数组原型的递归方法Array.prototype.reduce()
reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。
reduce()函数接收4个参数:
Accumulator
(acc) (累计器)Current Value
(cur) (当前值)Current Index
(idx) (当前索引)Source Array
(src) (源数组)
reduce()语法
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
简写看就是arr.reduce(callback,[initialValue])
reduce()参数
callback
执行数组中每个值 (如果没有提供 initialValue则第一个值除外)的函数,包含四个参数:
accumulator 累计器
累计回调的返回值; 它是上一次调用回调时返回的累积值,或initialValue
(见于下方)。
currentValue
数组中正在处理的元素。
index
可选 数组中正在处理的当前元素的索引。 如果提供了initialValue
,则起始索引号为0,否则从索引1起始。
array
可选 调用reduce()
的数组
-
initialValue
可选
作为第一次调用 callback函数时的第一个参数的值。 如果没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用 reduce 将报错。 -
返回值
函数累计处理的结果
官方给出了累加的示例
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
这是一些示例方法
export default {
mixins: [],
inject: [],
components: {
},
data () {
return {
arr: [1, 2, 3, 4, 5],
b: [1, 3, 4, 6, 7, 1, 3, 5, 3, 2, 4, 1, 2, 4, 5]
}
},
created() {
this.init()
},
methods: {
init() {
const a = this.arr
console.warn(a.reduce((a, b) => a + b)); // 递归求和15
console.warn(a.reduce((a, b) => a > b ? a : b)); // 递归求最大值5
console.warn(a.reduce((a, b) => a < b ? a : b)); // 递归求最小值1
const b = this.b.reduce((a, b) => {
if(!a.includes(b)) {
return a.concat(b)
}else{
return a
}
}, [])
console.warn(b); // 数组去重[1, 3, 4, 6, 7, 5, 2]
const c = this.b.reduce((a, b) => {
if(b in a) {
a[b]++
}else{
a[b] = 1
}
return a
}, {})
console.log('次数', c) // {1: 3, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1, 7: 1}
},
test() {
}
}
}