JavaScript控制台中的“-infinity”是什么意思?

8
我正在学习JavaScript ES6,当我运行以下代码时,在控制台上出现了“-infinity”:
```javascript console.log(-1 * Infinity); ```

let numeros = [1, 5, 10, 20, 100, 234];
let max = Math.max.apply(numeros);
console.log(max);

这是什么意思?

敬礼


2
如果Math.max没有传递任何值,它会返回可能的最小值,即-Infinity。参见:console.log(Math.max())。https://www.ecma-international.org/ecma-262/9.0/index.html#sec-math.max - Felix Kling
2个回答

8

Function#apply 的第一个参数是 thisArg,而你只是将 thisArg 作为数组传递,这意味着它在没有任何参数的情况下调用了 Math#max

根据 MDN 文档 :

如果未提供参数,则结果为 -Infinity。

为了解决问题,请将 Mathnull 设置为 thisArg

let max= Math.max.apply(Math, numeros );

let numeros= [1,5,10,20,100,234];
    let max= Math.max.apply(Math, numeros );
    
    console.log( max );


正如@FelixKling所建议的那样,从ES6开始,您可以使用扩展语法来提供参数。

Math.max(...numeros)

let numeros = [1, 5, 10, 20, 100, 234];
let max = Math.max(...numeros);

console.log(max);


1
由于这是 ES6,你可以使用Math.max(...numeros) - Felix Kling
哦...看起来min函数返回的是相反的结果。 - Get Off My Lawn
@GetOffMyLawn:是的,如果没有给出参数,结果就是无穷大。 (https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Math/min) - Pranav C Balan

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接