Lodash - meanBy 方法

语法

_.meanBy(array, [iteratee=_.identity])

此方法与 _.mean 类似,不同之处在于它接受 iteratee,它会针对数组中的每个元素调用 iteratee 来生成要平均的值。 iteratee 使用一个参数调用:(value)。

参数

  • array (Array) − 要迭代的数组。

  • [iteratee=_.identity] (Function) −每个元素调用的迭代器。

输出

  • (number) − 返回平均值。

示例

var _ = require('lodash');
var values = [{ 'n': 1 }, { 'n': 2 }, { 'n': 3 }];
var result = _.meanBy(values, function(item) { return item.n; });

console.log(result);
 
result = _.meanBy(values, 'n');
console.log(result);

将上述程序保存在tester.js中。运行以下命令执行该程序。

命令

\>node tester.js

输出

2
2

lodash_math.html