TypeScript 和数组归约函数

新手上路,请多包涵

你知道 reduce 数组方法在 TypeScript 中的作用吗?你能提供一个简单的使用例子吗?

我在 Google 和 TypeScript 语言规范 上进行了搜索,但找不到任何体面的解释和示例。

原文由 Tom 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 354
2 个回答

它实际上是 JavaScript 数组 reduce 函数,而不是特定于 TypeScript 的东西。

文档中所述对累加器和数组的每个值(从左到右)应用一个函数,以将其减少为单个值。

这是一个汇总数组值的示例:

 let total = [0, 1, 2, 3].reduce((accumulator, currentValue) => accumulator + currentValue);
console.log(total);

该片段应产生 6

原文由 JohnnyHK 发布,翻译遵循 CC BY-SA 4.0 许可协议

+1 @JohnnyHK 回答它是标准的 Javascript 函数。

我来到这里是因为我在输入这个函数时遇到了一些问题,所以我会把我的发现留在这里。如果你有一个标准的 IDE,如果你点击 reduce 函数,你会得到它的类型定义。

 /**
 * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
 * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
 * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
 */
reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;
reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;

/**
 * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
 * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
 * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
 */
reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;

第一组用于将 T 的数组减少为 T 值本身。

@Quentin 提到的还有第二种用法,即您可能希望将 T 的数组减少为其他类型。大多数情况下,我看到它被用作:

 const keyToValMap = [{key: 'k1', val: 1}].reduce<Record<string, number>>((map, el) => {
  map[el.key] = el.val;
  return map
}, {})

原文由 Kangur 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进