[英]what is the equivalent of a reduce in javascript
我是一個后端開發人員,最近轉移到了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函數將返回:
true && true
,其中第一個true是傳遞給reduce的初始值。 true && true
,這里的第一個true是先前結果的結果。 true && true
在歸約結束時,您只剩下一個布爾值,代表整個值的有效性,如果只有一個輸入組件的有效性為false,則整個歸約值將為false。 這是因為validSoFar
會跟蹤總體有效性,並通過返回到目前為止該形式是否有效以及迭代中當前輸入的有效性的復合值來進行變異。
在那里使用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函數中發現任何副作用開始的示例。
這是一個合理的等效項:
var validExpense = true;
var inputCmps = component.find('expenseform')
for (var i = 0; i < inputCmps.length; i++) {
// Displays error messages for invalid fields
inputCmp.showHelpMessageIfInvalid();
if (!inputCmp.get('v.validity').valid) {
validExpense = false;
}
}
// Now we can use validExpense
老實說,這是reduce
的一種奇怪用法,因為它的作用不只是將列表簡化為單個值。 它還可能在showHelpMessageIfInvalid()
的調用中產生副作用(大概showHelpMessageIfInvalid()
。
reduce
的想法很簡單。 給定要一次折疊為一個值(相同或任何其他類型)的值的列表,您可以提供一個函數,該函數采用當前折疊值和下一個列表值並返回新的折疊值和你提供初始折疊值,並reduce
通過調用與每一個連續的列表值和當前值折疊的功能將它們組合。
因此,例如
var items = [
{name: 'foo', price: 7, quantity: 3},
{name: 'bar', price: 5, quantity: 5},
{name: 'baz', price: 19, quantity: 1}
]
const totalPrice = items.reduce(
(total, item) => total + item.price * item.quantity, // folding function
0 // initial value
); //=> 65
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.