【问题标题】:javascript console -infinity, what does it mean?javascript控制台-infinity,这是什么意思?
【发布时间】:2019-03-19 16:24:31
【问题描述】:

我正在学习 javascript ES6,当我运行此代码时,我刚刚在控制台上发现了 -infinity:

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

什么意思?

问候

【问题讨论】:

标签: javascript ecmascript-6 console


【解决方案1】:

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

根据MDN docs :

如果没有给出参数,则结果为 -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 开始,您可以使用spread syntax 来提供参数。

Math.max(...numeros)

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

console.log(max);

【讨论】:

【解决方案2】:

改用ES6 Spread

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

正如@Pranav C Balan 已经提到的,-InfinityMath.max() 在没有给出参数的情况下应该返回的(由规范定义):

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max#Description

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多