javascript - 什么相当于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
.
有人可以对这里发生的事情有所了解吗?我应该在我的日常工作中经常使用它。
谢谢
解决方案
在那里使用 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 函数中引发副作用的例子。
推荐阅读
- slim-lang - Slim 模板和 TailwindCSS 在类声明中使用 ' : '
- php - 身份验证尝试不起作用,但数据将存储在用户中
- php - 如何将 XML 文件放到 MYSQL 和 MYSQL 文件到 XML
- html - URL 片段可以指向没有 id 的 HTML 元素吗?
- amazon-web-services - 无法在 python 中使用来自 AWS Lambda 的 Boto3 客户端调用 SageMaker 端点(TensorFlow 模型)
- java - 世界杯板球比赛直播 API
- c# - C# - 没有简单的方法将十六进制和 ASCII 连接成一个字符串
- joomla - 使用多个表单字段进行服务器端验证
- sqlite - FDPhysSQLiteDriverLink 的目的是什么?
- html - 地点 Google api 自动完成 -> 不显示街道内的数字