泛型
wabicai
# 泛型
# 实战
- 原生的Reduce方法
function customReduce<T, U>(array: T[], callback: (accumulator: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U {
let accumulator: U = initialValue;
for (let i = 0; i < array.length; i++) {
accumulator = callback(accumulator, array[i], i, array);
}
return accumulator;
}
// 示例用法
const numbers = [1, 2, 3, 4, 5];
const sum = customReduce(numbers, (acc, curr) => acc + curr, 0);
console.log(sum); // 输出: 15
const product = customReduce(numbers, (acc, curr) => acc * curr, 1);
console.log(product); // 输出: 120
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19