簡體   English   中英

Reduce和三元運算符。reduce方法中的三元運算符在'else'部分為零並返回錯誤答案

[英]Reduce and ternary operator .The ternary operator in reduce method has zero in the 'else' part and return the wrong answer

我的 reduce function 返回 27 而不是 77。我想知道為什么會這樣。 我不是在尋找解決方案。 我知道解決方案,但我不知道為什么我的三元運算符的 else 部分中的 0 或 null 沒有給出正確答案。

const sumFive = arr => arr.reduce((sum, value) => value > 5 ? sum + value : 0, 0)

sumFive([1, 5, 20, 30, 4, 9, 18])

每次迭代遇到 5 或更小的值時,您都將累加器重置為 0。

iteration so far --- accumulator returned by iteration

1 --- 0
1, 5 --- 0
1, 5, 20 --- 20
1, 5, 20, 30 --- 50
1, 5, 20, 30, 4 --- 0
1, 5, 20, 30, 4, 9 --- 9
1, 5, 20, 30, 4, 9, 18 --- 27

如果您希望 function 產生所需的 output,則需要返回當前累加器值而不是 0。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM