javascript 如何使用 underscore.js reduce 方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7524575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use underscore.js reduce method?
提问by Chapsterj
anyone got any examples on how to use the reduce method in underscore.
任何人都有关于如何在下划线中使用 reduce 方法的任何示例。
回答by kennebec
Here are two javascript examples, quite similar to underscore.
这是两个 javascript 示例,与下划线非常相似。
These find the mathematical mean and the standard deviation in an array of numbers.
它们在一组数字中找到数学平均值和标准偏差。
You often see reduce working with thousands or millions of items in arrays related to populatons or statistics.
您经常会看到 reduce 处理与人口或统计数据相关的数组中的数千或数百万个项目。
Math.mean= function(array){
return array.reduce(function(a, b){return a+b;})/array.length;
}
Math.stDeviation= function(array){
var mean= Math.mean(array),
dev= array.map(function(itm){return (itm-mean)*(itm-mean);});
return Math.sqrt(dev.reduce(function(a, b){return a+b;})/array.length);
}
var A2= [6.2, 5, 4.5, 6, 6, 6.9, 6.4, 7.5];
alert ('mean: '+Math.mean(A2)+'; deviation: '+Math.stDeviation(A2))
/* returned value: (String)
mean: 6.0625; deviation: 0.899913190257816
*/
回答by NilColor
They have it... http://underscorejs.org/#reduceRight there - at the official Underscore.js site.
他们有它... http://underscorejs.org/#reduce就在那里 - 在 Underscore.js 官方网站上。