【问题标题】:Reason of using -Infinity in reduce在 reduce 中使用 -Infinity 的原因
【发布时间】:2018-06-15 05:01:50
【问题描述】:

所以我正在阅读一些函数式编程并且有一个:

const max = xs => reduce((acc, x) => (x >= acc ? x : acc), -Infinity, xs);

您能在这里解释一下-Infinity的确切作用是什么吗?

【问题讨论】:

    标签: javascript ecmascript-6 infinity


    【解决方案1】:

    它可能是为了模仿 Math.max 的行为,在不带参数调用时返回 -infinity

    console.log(Math.max());

    同样,使用您的max 函数,使用空数组调用max 将导致-infinity

    const max = xs => xs.reduce((acc, x) => (x >= acc ? x : acc), -Infinity, xs);
    console.log(max([]));

    不过,在大多数情况下,它并不是 有用,它可能只是为了在空数组上调用时与其他任何东西(例如抛出错误,或返回0null)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-22
      • 2018-07-27
      • 2017-09-11
      • 1970-01-01
      • 2017-07-23
      • 2021-12-09
      • 2018-08-08
      • 1970-01-01
      相关资源
      最近更新 更多