【发布时间】:2018-06-15 05:01:50
【问题描述】:
所以我正在阅读一些函数式编程并且有一个:
const max = xs => reduce((acc, x) => (x >= acc ? x : acc), -Infinity, xs);
您能在这里解释一下-Infinity的确切作用是什么吗?
【问题讨论】:
标签: javascript ecmascript-6 infinity
所以我正在阅读一些函数式编程并且有一个:
const max = xs => reduce((acc, x) => (x >= acc ? x : acc), -Infinity, xs);
您能在这里解释一下-Infinity的确切作用是什么吗?
【问题讨论】:
标签: javascript ecmascript-6 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([]));
不过,在大多数情况下,它并不是 有用,它可能只是为了在空数组上调用时与其他任何东西(例如抛出错误,或返回0 或null)。
【讨论】: