2015-04-07 204 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