86

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

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

4

6 回答 6

124

除了其他答案之外,只是一个注释。

如果提供了一个初始值来减少,那么有时必须指定它的类型,即:-

a.reduce(fn, [])

可能必须是

a.reduce<string[]>(fn, [])

或者

a.reduce(fn, <string[]>[])
于 2017-11-24T13:54:58.193 回答
74

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

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

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

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

该片段应该产生6.

于 2012-12-30T02:00:57.647 回答
18

使用 TypeScript 泛型,你可以做这样的事情。

class Person {
    constructor (public Name : string, public Age: number) {}
}

var list = new Array<Person>();
list.push(new Person("Baby", 1));
list.push(new Person("Toddler", 2));
list.push(new Person("Teen", 14));
list.push(new Person("Adult", 25));

var oldest_person = list.reduce( (a, b) => a.Age > b.Age ? a : b );
alert(oldest_person.Name);
于 2015-09-12T13:32:55.117 回答
9

减少()是..

  • reduce() 方法将数组缩减为单个值。
  • reduce() 方法为数组的每个值(从左到右)执行提供的函数。
  • 函数的返回值存储在累加器中(结果/总计)。

它是 ..

let array=[1,2,3];
function sum(acc,val){ return acc+val;} // => can change to (acc,val)=>acc+val
let answer= array.reduce(sum); // answer is 6

改成

let array=[1,2,3];
let answer=arrays.reduce((acc,val)=>acc+val);

您也可以在

  1. 找到最大值
    let array=[5,4,19,2,7];
    function findMax(acc,val)
    {
     if(val>acc){
       acc=val; 
     }
    }

    let biggest=arrays.reduce(findMax); // 19
  1. 找到一个不重复的元素
    arr = [1, 2, 5, 4, 6, 8, 9, 2, 1, 4, 5, 8, 9]
    v = 0
    for i in range(len(arr)):
    v = v ^ arr[i]
    print(value)  //6
于 2019-06-05T04:31:12.297 回答
0

计算数值数组乘积的简单示例。我总是忘记的位是variable as type作为初始累加器传递的参数的语法。

const product = (nums: number[]): number => nums.reduce((acc: number, v: number): number => acc * v, 1 as number);
alert(product([1, 2, 3, 4]));
于 2022-01-05T12:17:26.400 回答
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;

第一组用于将数组减少TT值本身。

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

const keyToValMap = [{key: 'k1', val: 1}].reduce<Record<string, number>>((map, el) => {
  map[el.key] = el.val;
  return map
}, {})
于 2022-03-03T13:55:47.757 回答