为何选择Math.min()> Math.max()? [英] Why Math.min() > Math.max()?
问题描述
当我在javascript数学最小和最大函数的参数中输入数组时,它返回正确的值:
When I type in an array into the parameter of the javascript math minimum and maximum functions, it returns the correct value:
console.log( Math.min( 5 ) ); // 5
console.log( Math.max( 2 ) ); // 2
var array = [3, 6, 1, 5, 0, -2, 3];
var minArray = Math.min( array ); // -2
var maxArray = Math.max( array ); // 6
但是,当我使用没有参数的函数时,它会返回一个错误的答案:
However, when I use the function with no parameters, it returns an incorrect answer:
console.log( Math.min() ); // Infinity
console.log( Math.max() ); // -Infinity
这个返回false:
console.log( Math.min() < Math.max() );
为什么会这样做?
Why does it do this?
推荐答案
当然会,因为无限
的起始编号Math.min
。低于正无穷大的所有数字应该是列表中最小的数字,如果没有更小的数字。
Of course it would, because the start number should be Infinity
for Math.min
. All number that are lower than positive infinity should be the smallest from a list, if there are no smaller.
对于 Math.max
它是一样的;如果没有更大的数字,所有大于负无穷大的数字应该是最大的。
And for Math.max
it's the same; all numbers that are larger than negative infinity should be the biggest if there are no bigger.
所以对于你的第一个例子:
So for your first example:
Math.min(5)
其中 5
小于正无穷大(无限
)它将返回 5
。
Math.min(5)
where 5
is smaller than positive infinity (Infinity
) it will return 5
.
使用数组参数调用 Math.min()
和 Math.max
可能不会在每个平台上工作。您应该执行以下操作:
Calling Math.min()
and Math.max
with an array parameter may not work on every platform. You should do the following instead:
Math.min.apply(null, [ 1, 2, 3, 4 , 5 ]);
第一个参数是范围参数。因为 Math.min()
和 Math.max()
是静态函数,我们应该设置范围参数为null。
Where the first parameter is the scope argument. Because Math.min()
and Math.max()
are "static" functions, we should set the scope argument to null.
这篇关于为何选择Math.min()> Math.max()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!