2012-12-30 138 views

回答

16

它实际上是JavaScript的数组reduce功能,而不是具体到打字稿的东西。

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

下面是其中总结了数组的值的打字稿例如:

total = [0, 1, 2, 3].reduce((a, b) => a + b); 
alert(total); 

alert框将显示6

+1

阿!这就是为什么我找不到与TypeScript有关的任何信息。非常感谢您的帮助! – Tom

6

随着打字稿泛型,你可以做这样的事情。

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); 
1

除了其他答案之外,还有一个附注。

如果初始值被提供,以减少然后有时必须指定其类型,即: -

a.reduce(fn, []) 

可能必须

a.reduce〈string[]〉(fn, []) 

a.reduce(fn, 〈string[]〉[]) 
+1

欢迎StackOverflow上:如果您发布的代码,XML或数据样本,请突出显示文本编辑器的线路,然后点击编辑器工具栏或用Ctrl + K的“代码示例”按钮({})在键盘上很好地格式和语法突出显示它! – WhatsThePoint

+1

这不提供问题的答案。一旦你有足够的[声誉](https://stackoverflow.com/help/whats-reputation),你将可以[对任何帖子发表评论](https://stackoverflow.com/help/privileges/comment);相反,[提供不需要提问者澄清的答案](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-c​​an- I-DO-代替)。 - [来自评论](/ review/low-quality-posts/18087822) – Melebius

+1

接受的答案省略了解释累加器可以用任何对象初始化,因此也可以是不同的类型。 –