在整数数组上返回

在整数数组上返回

本文介绍了为什么 math.max() 在整数数组上返回 NaN?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从一个简单的数组中获得最大的数字:

I am trying to get the highest number from a simple array:

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:

如果至少有一个参数不能转换为数字,则结果为 NaN.

在您的实例中,您只提供 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.

展开数组

您还可以展开数组.这基本上将数组视为每个项目都作为它自己的参数被传递.

You can also spread the array. This essentially treats the array as if each item is being passed as it's own argument.

Math.max(...data);

这篇关于为什么 math.max() 在整数数组上返回 NaN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 09:59