问题描述
我想从一个简单的数组获得最高数字
:
data = [4, 2, 6, 1, 3, 7, 5, 3];
alert(Math.max(data));
我已经读过如果数组中的其中一个值无法转换为数字,它将返回 NaN
,但在我的情况下,我已经用 typeof
进行了双重检查,以确保它们都是数字那么我的问题是什么呢?
I have read that if even one of the values in the array can't be converted to number, it will return NaN
, but in my case, I have double-checked with typeof
to make sure they are all numbers, so what can be my problem?
推荐答案
您的代码不起作用的原因是因为 Math.max
期望每个参数都是有效数字。这在中指出如下:
The reason why your code doesn't work is because Math.max
is expecting each parameter to be a valid number. This is indicated in the documentation as follows:
在你的实例中,你只提供1个参数,而1个值是一个数组而不是一个数字(它没有检查数组中的内容,它只是停在知道它不是一个有效的数字。)
In your instance you are only providing 1 argument, and that 1 value is an array not a number (it doesn't go as far as checking what is in an array, it just stops at knowing it isn't a valid number).
一种可能的解决方案是通过传递一个参数数组来显式调用该函数。像这样:
One possible solution is to explicitly call the function by passing an array of arguments. Like so:
Math.max.apply(Math, data);
这实际上与您手动指定不带数组的每个参数相同:
What this effectively does is the same as if you manually specified each argument without an array:
Math.max(4, 2, 6, 1, 3, 7, 5, 3);
正如您所看到的,每个参数现在都是一个有效数字,因此它将按预期工作。
And as you can see, each argument is now a valid number, so it will work as expected.
这篇关于为什么math.max()返回带有整数数组的NaN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!