← 中文资源

简体中文版本

空展开的 Math.max 得到 -Infinity

空数组展开给 Math.max/min 时不剩任何实参:max 返回 -Infinity、min 返回 Infinity;只要混进一个 NaN 整个结果就被污染,归约时可用 -Infinity 当初值。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

max of empty: -Infinity
min of empty: Infinity
best: 98
worst: 12
with NaN: NaN
reduced best: 98

实现说明

顶层就这几处状态:scores、best。

使用要点

  • 每一步打印都带着自己的标签:max of empty:、min of empty:、best:。

常见问题

运行前要先安装什么?

什么都不用额外装——运行时自带了代码所需的一切。 文件用顶层绑定保存自己的状态:scores、best。

核心语句

const best = scores.reduce((acc, n) => Math.max(acc, n), -Infinity);

代码示例

// Spread of an empty array gives Math.max/min no arguments at all
console.log('max of empty:', Math.max(...[]));
console.log('min of empty:', Math.min(...[]));

// With values, spread replaces the old apply(this, arr) idiom
const scores = [12, 98, 45];
console.log('best:', Math.max(...scores));
console.log('worst:', Math.min(...scores));

// A single NaN poisons the whole result
console.log('with NaN:', Math.max(...scores, NaN));

// -Infinity is the identity for max: safe seed when reducing by hand
const best = scores.reduce((acc, n) => Math.max(acc, n), -Infinity);
console.log('reduced best:', best);