Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在JavaScript中使用Math.max()函数时如何避免NaN?_Javascript - Fatal编程技术网

在JavaScript中使用Math.max()函数时如何避免NaN?

在JavaScript中使用Math.max()函数时如何避免NaN?,javascript,Javascript,我正在尝试获取数字数组中的最大值: maxtime=Math.max.apply( Math, cnttimearr ); alert(maxtime); 但是,我得到的是NaN,而不是最大值。谁能告诉我我做错了什么吗 如果至少有一个参数无法转换为数字,则结果为NaN 确保数组中的所有元素都可转换为数字 > xs = [1, 2, '3']; [1, 2, "3"] > Math.max.apply(Math, xs); 3 > xs = [1, 2, 'hello']; [

我正在尝试获取数字数组中的最大值:

maxtime=Math.max.apply( Math, cnttimearr );
alert(maxtime);
但是,我得到的是
NaN
,而不是最大值。谁能告诉我我做错了什么吗

如果至少有一个参数无法转换为数字,则结果为
NaN

确保数组中的所有元素都可转换为数字

> xs = [1, 2, '3'];
[1, 2, "3"]
> Math.max.apply(Math, xs);
3
> xs = [1, 2, 'hello'];
[1, 2, "hello"]
> Math.max.apply(Math, xs);
NaN

检查您的数组
cnttimearr
,确保所有值都可以转换为数字


什么是
cnttimearr
?还要编写
cnttimearr
的定义
cnttimearr= [5, 6, 2, 3, 7];    /*your array should be like this */

maxtime = Math.max.apply(Math, cnttimearr); 
/* This about equal to Math.max(cnttimearr[0], ...) or Math.max(5, 6, ..) */
alert(maxtime);