如何防止Math.max()返回NaN?
问题描述:
我想创建一个函数,它返回一个数组中的最大数字,但它一直返回NaN
。如何防止Math.max()返回NaN?
如何防止NaN并返回想要的结果?
var thenum = [5,3,678,213];
function max(num){
console.log(Math.max(num));
}
max(thenum);
答
为什么发生这种情况的原因是,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是既
答
一个的jsfiddle试试这个。 Math.max.apply(Math,thenum)
var thenum = [5,3,678,213];
function max(num){
console.log(Math.max.apply(Math,thenum));
}
结果:678
答
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());
答
的Math.max()方法不允许你在阵列中传递。因此对于数组,您必须使用Function.prototype.apply(),例如
Math.max.apply(null, Array);
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply