简体   繁体   中英

How to use underscore.js reduce method?

任何人都有关于如何在下划线中使用reduce方法的任何示例。

Here are two javascript examples, quite similar to underscore.

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.

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
*/

他们有它...... http://underscorejs.org/#reduce就在那里 - 在官方的Underscore.js网站上。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM