为什么 math.max() 在整数数组上返回 NaN?
Why is math.max() returning NaN on an array of integers?
我正在尝试从一个简单数组中获取最大数:
data = [4, 2, 6, 1, 3, 7, 5, 3];
alert(Math.max(data));
我读到即使数组中的一个值无法转换为数字,它也会 return NaN
,但就我而言,我已经仔细检查过typeof
确保它们都是数字,那么我的问题是什么?
如果您查看 Math.max 的文档,您可以查看下一个描述
Because max() is a static method of Math, you always use it as Math.max(), rather than as a method of a Math object you created (Math is not a constructor).
If no arguments are given, the result is -Infinity.
If at least one of arguments cannot be converted to a number, the result is NaN.
当您调用 Math.max
时使用像
这样的数组参数
Math.max([1,2,3])
你用 一个 参数调用这个函数 - [1,2,3]
和 javascript 尝试将它转换为数字并得到 ("1,2,3" - > NaN) 失败。
所以结果符合预期 - NaN
注意: 如果数组只有 一个 数字 - 所有工作正常
Math.max([23]) // return 23
因为 [23] -> "23" -> 23
并且转换为 Number 已经完成。
如果你想从数组中获取最大元素,你应该使用 apply 函数,比如
Math.max.apply(Math,[1,2,3])
或者您可以使用 new spread operator
Math.max(...[1,2,3])
您的代码不起作用的原因是因为 Math.max
期望每个参数都是有效数字。这在documentation中表示如下:
If at least one of arguments cannot be converted to a number, the result is NaN.
在您的实例中,您只提供了 1 个参数,而这 1 个值是一个数组而不是一个数字(它不会检查数组中的内容,它只是知道它不是一个有效的数字)。
一种可能的解决方案是通过传递参数数组来显式调用该函数。像这样:
Math.max.apply(Math, data);
这有效地执行的操作与您在没有数组的情况下手动指定每个参数相同:
Math.max(4, 2, 6, 1, 3, 7, 5, 3);
如您所见,每个参数现在都是一个有效数字,因此它将按预期工作。
展开数组
你也可以spread the array。这实质上将数组视为每个项目都作为其自己的参数传递。
Math.max(...data);
如果你必须使用Math.max函数并且数组中的一个数字可能未定义,你可以使用:
x = Math.max(undefined || 0, 5)
console.log(x) // prints 5
它不起作用,因为您传递的是数组作为参数而不是逗号分隔的数字。尝试像这样展开数组:
data = [4, 2, 6, 1, 3, 7, 5, 3];
alert(Math.max(...data));
我正在尝试从一个简单数组中获取最大数:
data = [4, 2, 6, 1, 3, 7, 5, 3];
alert(Math.max(data));
我读到即使数组中的一个值无法转换为数字,它也会 return NaN
,但就我而言,我已经仔细检查过typeof
确保它们都是数字,那么我的问题是什么?
如果您查看 Math.max 的文档,您可以查看下一个描述
Because max() is a static method of Math, you always use it as Math.max(), rather than as a method of a Math object you created (Math is not a constructor).
If no arguments are given, the result is -Infinity.
If at least one of arguments cannot be converted to a number, the result is NaN.
当您调用 Math.max
时使用像
Math.max([1,2,3])
你用 一个 参数调用这个函数 - [1,2,3]
和 javascript 尝试将它转换为数字并得到 ("1,2,3" - > NaN) 失败。
所以结果符合预期 - NaN
注意: 如果数组只有 一个 数字 - 所有工作正常
Math.max([23]) // return 23
因为 [23] -> "23" -> 23
并且转换为 Number 已经完成。
如果你想从数组中获取最大元素,你应该使用 apply 函数,比如
Math.max.apply(Math,[1,2,3])
或者您可以使用 new spread operator
Math.max(...[1,2,3])
您的代码不起作用的原因是因为 Math.max
期望每个参数都是有效数字。这在documentation中表示如下:
If at least one of arguments cannot be converted to a number, the result is NaN.
在您的实例中,您只提供了 1 个参数,而这 1 个值是一个数组而不是一个数字(它不会检查数组中的内容,它只是知道它不是一个有效的数字)。
一种可能的解决方案是通过传递参数数组来显式调用该函数。像这样:
Math.max.apply(Math, data);
这有效地执行的操作与您在没有数组的情况下手动指定每个参数相同:
Math.max(4, 2, 6, 1, 3, 7, 5, 3);
如您所见,每个参数现在都是一个有效数字,因此它将按预期工作。
展开数组
你也可以spread the array。这实质上将数组视为每个项目都作为其自己的参数传递。
Math.max(...data);
如果你必须使用Math.max函数并且数组中的一个数字可能未定义,你可以使用:
x = Math.max(undefined || 0, 5)
console.log(x) // prints 5
它不起作用,因为您传递的是数组作为参数而不是逗号分隔的数字。尝试像这样展开数组:
data = [4, 2, 6, 1, 3, 7, 5, 3];
alert(Math.max(...data));