为什么在ES2015中Math.max(... [])等于-Infinity?

为什么在ES2015中Math.max(... [])等于-Infinity?

问题描述:

Math.max([])将为 0

[.. []] []

但是为什么 Math.max(... [])在ES2015中等于 -Infinity

But why Math.max(...[]) is equal to -Infinity in ES2015?

Math.max([])会发生什么? [] 首先转换为字符串,然后转换为数字。实际上,它不是参数数组。

What happens with Math.max([]) is that [] is first converted to a string and then to a number. It is not actually considered an array of arguments.

Math.max(... [])一起,该数组被视为通过点差组成的参数集合操作员。由于数组为空,因此这与不带参数的调用相同。
根据 docs a>产生-Infinity

With Math.max(...[]) the array is considered a collection of arguments through the spread operator. Since the array is empty, this is the same as calling without arguments. Which according to the docs produces -Infinity


如果未给出参数,则结果为-Infinity。

If no arguments are given, the result is -Infinity.

一些例子显示了数组调用的区别:


Some examples to show the difference in calls with arrays:

console.log(+[]); //0    [] -> '' -> 0
console.log(+[3]); //3    [] -> '3' -> 3
console.log(+[3,4]); //Nan 
console.log(...[3]); //3
console.log(...[3,4]); //3 4 (the array is used as arguments)
console.log(Math.max([])); //0  [] is converted to 0
console.log(Math.max()); // -infinity:  default without arguments
console.log(Math.max(...[])); // -infinity
console.log(Math.max([3,4])); //Nan
console.log(Math.max(...[3,4])); //4