gpt4 book ai didi

javascript - 在 reduce 中使用 -Infinity 的原因

转载 作者:行者123 更新时间:2023-11-29 10:29:11 24 4
gpt4 key购买 nike

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

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

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

最佳答案

它可能是为了模仿 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)。

关于javascript - 在 reduce 中使用 -Infinity 的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50869359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com