2015-04-07 59 views
3

我想创建一个函数,它返回一个数组中的最大数字,但它一直返回NaN如何防止Math.max()返回NaN?

如何防止NaN并返回想要的结果?

var thenum = [5,3,678,213]; 

function max(num){ 
    console.log(Math.max(num)); 
} 

max(thenum);                  

回答

4

为什么发生这种情况的原因是,Math.max计算最大出它的参数。并且看到第一个参数是一个Array,它返回NaN。但是,您可以使用apply方法调用它,该方法允许您调用函数并在数组内为它们发送参数。

更多关于the apply method

所以,你想要的是应用Math.max功能,像这样:

var thenum = [5, 3, 678, 213]; 

function max(num){ 
    return Math.max.apply(null, num); 
} 

console.log(max(thenum)); 

你也可以把它的方法和它连接到阵列的原型。这样你可以更容易和更清洁地使用它。像这样:

Array.prototype.max = function() { 
    return Math.max.apply(null, this); 
}; 
console.log([5, 3, 678, 213].max()); 

而且here是既

1

一个的jsfiddle试试这个。 Math.max.apply(Math,thenum)

var thenum = [5,3,678,213]; 

function max(num){ 
    console.log(Math.max.apply(Math,thenum)); 
} 

结果:678

0
var p = [35,2,65,7,8,9,12,121,33,99]; 

Array.prototype.max = function() { 
    return Math.max.apply(null, this); 
}; 

Array.prototype.min = function() { 
    return Math.min.apply(null, this); 
}; 


alert("Max value is: "+p.max()+"\nMin value is: "+ p.min()); 

demo