我是一名業余的編碼員,是減速器的新手。
我有一個應用程式,它將物件添加到一個陣列中,并通過還原器來捕獲每個物件的位置值的數量。
下面的方法在一定程度上起作用,當我添加兩個'Att'物體時,totalAtt 的數量等于兩個,但是當我添加另一個位置值時,totalAtt 的數量被重置為零。同樣,所有的位置值也是如此。
發現&&運算子將我的初始值重置為假,因為它具有布爾性質。
有誰知道如何調整代碼,以便在不重設值的情況下捕獲數量?
const totalGK = get( team).reduce(
(a, b) => b.position =="GK" && a b.qty。
0
);
const totalDef = get( team).reduce(
(a, b) => b.position =="def" && a b.qty。
0
);
const totalMid = get( team).reduce(
(a, b) => b.position =="mid" && a b.qty。
0
);
const totalAtt = get( team).reduce(
(a, b) => b.position =="Att" && a b.qty。
0?
);
return {
totalGK,
totalDef,
totalMid,
totalAtt
};
}
uj5u.com熱心網友回復:
當減少時,你總是回傳累加器的新值。在你的例子中,你在之前的累加器上加了一個值來得到新的值。所以你應該總是取a(累加器),然后加上0(b.position == something是false,所以它被投到0)或者如果條件是true的數字。
const totalGK = get( team).reduce(
(a, b) => a (b.position =="GK" && b.qty) 。
0 0
);
const totalDef = get( team).reduce(
(a, b) => a (b.position =="def" && b.qty) 。
0>
);
const totalMid = get( team).reduce(
(a, b) => a (b.position =="Mid" && b.qty) 。
0
);
const totalAtt = get( team).reduce(
(a, b) => a (b.position =="Att" && b.qty) 。
0>
);
然而,有一個更短、更易讀的方法,將team還原成一個物件,使用position值作為鍵,并將qty添加到鍵的前一個值中。要獲得常量,請對由 reduce 創建的物件進行解構,并使用 0 作為默認值。
例子:
。const get = arr => arr;
const team = [{ position: 'GK', qty: 2 }, { position: 'GK', qty: 2 }, { position: 'GK', qty: 2 }, { position: 'Att', qty: 3 }, { position: 'Att', qty: 3 }, { position: 'Att', qty: 3 }]。
const {
GK: totalGK = 0,
Def: totalDef = 0,
Mid: totalMid = 0,
Att: totalAtt = 0,
} = get(team).reduce((acc, obj) =>({.
...acc。
[obj.position]: (acc[obj.position] || 0) obj.qty] obj.qty.
}), {});
console.log(totalGK); / 6
console.log(totalDef); // 0
console.log(totalMid); / 0
console.log(totalAtt); / 9
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
使用三元運算子效果會更好,所以你總是從你的函式中回傳一個值。像這樣
const totalGK = get( team).reduce(
(a, b) => b.position =="GK" ? a b.qty : a。
0 ?
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/312757.html
標籤:
