首页 > 解决方案 > 什么相当于javascript中的reduce

问题描述

我是最近搬到 js 方面的后端开发人员。我正在阅读教程,并遇到了下面的代码。

clickCreate: function(component, event, helper) {
    var validExpense = component.find('expenseform').reduce(function (validSoFar, inputCmp) {
        // Displays error messages for invalid fields
        inputCmp.showHelpMessageIfInvalid();
        return validSoFar && inputCmp.get('v.validity').valid;
    }, true);
    // If we pass error checking, do some real work
    if(validExpense){
        // Create the new expense
        var newExpense = component.get("v.newExpense");
        console.log("Create expense: " + JSON.stringify(newExpense));
        helper.createExpense(component, newExpense);
    }
}

在这里,我试图了解很多关于正在发生的事情,有一种reduce叫做validSoFar. 我无法理解引擎盖下发生了什么。:-(

我确实得到了在Java.

有人可以对这里发生的事情有所了解吗?我应该在我的日常工作中经常使用它。

谢谢

标签: javascript

解决方案


在那里使用 reduce 是没有意义的,并且在 reduce 中有副作用。最好使用Array.prototype.filter来获取所有无效的费用项目。

然后使用Array.prototype.forEach为每个无效项目产生副作用。然后,您可以检查无效费用项目数组的长度,以查看您的输入是否有效:

function(component, event, helper) {
  var invalidExpenses = component.find('expenseform').filter(
    function(ex){
      //return not valid (!valid)
      return !ex.get('v.validity').valid
    }
  );
  invalidExpenses.forEach(
    //use forEach if you need a side effect for each thing
    function(ex){
      ex.showHelpMessageIfInvalid();
    }
  );
  // If we pass error checking, do some real work
  if(invalidExpenses.length===0){//no invalid expense items
      // Create the new expense
      var newExpense = component.get("v.newExpense");
      console.log("Create expense: " + JSON.stringify(newExpense));
      helper.createExpense(component, newExpense);
  }
}

Array.prototype.reduce的mdn 文档对如何使用它有很好的描述和示例。

它应该接受一系列事物并返回另一个事物(可以是不同类型的事物)。但是你不会在那里找到任何在 reducer 函数中引发副作用的例子。


推荐阅读