为什么math.max()在整数数组上返回NaN? [英] Why is math.max() returning NaN on an array of integers?

查看:626
本文介绍了为什么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.

If at least one of arguments cannot be converted to a number, the result is 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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆