【问题标题】:Reduce and ternary operator .The ternary operator in reduce method has zero in the 'else' part and return the wrong answerReduce和三元运算符。reduce方法中的三元运算符在'else'部分为零并返回错误答案
【发布时间】:2021-05-02 05:37:26
【问题描述】:

我的 reduce 函数返回 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])

【问题讨论】:

  • 这是做什么用的?
  • 如果您返回0,它会重置总和。也许您打算返回sum

标签: javascript reduce ternary


【解决方案1】:

每次迭代遇到小于或等于 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

如果您希望函数产生所需的输出,则需要返回当前累加器值而不是 0。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    • 2021-01-03
    • 1970-01-01
    • 2011-04-03
    • 2012-11-19
    • 2012-10-01
    相关资源
    最近更新 更多