📜  Lodash _.sumBy() 方法

📅  最后修改于: 2022-05-13 01:56:25.406000             🧑  作者: Mango

Lodash _.sumBy() 方法

Lodash是一个基于 underscore.js 的 JavaScript 库。 Lodash 有助于处理数组、字符串、对象、数字等。

_.sumBy()方法用于通过使用 Iteratee函数迭代数组中的每个元素来计算原始数组的总和。它与 _.sum() 方法几乎相同。

句法:

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

参数:此方法接受上面提到的两个参数,如下所述:

  • array:此参数保存要迭代的数组。
  • [iteratee = _.identity]:此参数保存每个元素调用的 iteratee。

返回值:此方法返回总和。

示例 1:这里使用 const _ = require('lodash') 将 lodash 库导入文件。

Javascript
// Requiring the lodash library  
const _ = require("lodash");  
   
// Original array 
var arr = [{ 'n': 4 }, { 'n': 2 }, { 'n': 6 }];
     
// Use of _.sumBy()  
// method 
let gfg = _.sumBy(arr, function(o) { return o.n; }); 
         
// Printing the output  
console.log(gfg);


Javascript
// Requiring the lodash library  
const _ = require("lodash");  
   
// Original array 
var arr = [{ 'n': 10 }, { 'n': 5 }, { 'n': 3 }, { 'n': 12 }];
     
// Use of _.sumBy()  
// method 
let gfg = _.sumBy(arr, 'n'); 
         
// Printing the output  
console.log(gfg);


输出:

12

示例 2:

Javascript

// Requiring the lodash library  
const _ = require("lodash");  
   
// Original array 
var arr = [{ 'n': 10 }, { 'n': 5 }, { 'n': 3 }, { 'n': 12 }];
     
// Use of _.sumBy()  
// method 
let gfg = _.sumBy(arr, 'n'); 
         
// Printing the output  
console.log(gfg);

输出:

30