LoDash: Reduce in Angular returns 0

LoDash: Reduce in Angular returns 0

本文关键字:returns Angular in Reduce LoDash      更新时间:2023-09-26

在Angular控制器中,我有:

$scope.corn = {
        acres: 347.4,
        fertilizer: {
            arm: 0,
            dist: 164.97,
            other: 0
        }
    };
    $scope.corn.fertilizer.total = _.reduce($scope.corn.fertilizer);
    console.log($scope.corn);

在控制台中,我看到这个:

acres: 347.4
fertilizer: Object
    arm: 0
    dist: 164.97
    other: 0
    total: 0

我确信"_.reduce()不起作用"的说法与事实相去甚远,因此,我将改为编写

有人能向新的LoDash用户展示如何使用_.reduce将totals变量添加到对象中吗?

提前感谢!

您希望在_.reduce调用中进行回调。它看起来像这样:

$scope.corn.fertilizer.total = _.reduce($scope.corn.fertilizer, function(total, num) {
  return total + num;
});

第一个参数是集合,第二个参数是回调。回调有几个参数,第一个是"accumulator"(如果没有定义,它将是集合的第一个元素,本例就是这样),第二个是集合中项的值,第三个是键或索引(不需要)。