Lodash - sumBy 方法

语法

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

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

参数

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

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

输出

  • (number) − 返回总和。

示例

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

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

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

命令

\>node tester.js

输出

6
6

lodash_math.html