Jma*_*nol 8 javascript console ecmascript-6
我正在学习JavaScript ES6,当我运行以下代码时,在控制台上发现了-infinity:
let numeros = [1, 5, 10, 20, 100, 234];
let max = Math.max.apply(numeros);
console.log(max);
Run Code Online (Sandbox Code Playgroud)
这是什么意思?
问候
的第一个参数Function#apply
是thisArg,您只是将thisArg
as作为数组传递,这意味着它在调用时Math#max
没有任何参数。
根据MDN文档:
如果未提供任何参数,则结果为-Infinity。
为了解决您的问题集Math
或null
如thisArg。
let max= Math.max.apply(Math, numeros );
Run Code Online (Sandbox Code Playgroud)
let max= Math.max.apply(Math, numeros );
Run Code Online (Sandbox Code Playgroud)
正如@FelixKling所建议的那样,从ES6开始,您可以使用传播语法来提供参数。
Math.max(...numeros)
Run Code Online (Sandbox Code Playgroud)
let numeros= [1,5,10,20,100,234];
let max= Math.max.apply(Math, numeros );
console.log( max );
Run Code Online (Sandbox Code Playgroud)