我想創建一個函數,它返回一個數組中的最大數字,但它一直返回NaN
。如何防止Math.max()返回NaN?
如何防止NaN並返回想要的結果?
var thenum = [5,3,678,213];
function max(num){
console.log(Math.max(num));
}
max(thenum);
我想創建一個函數,它返回一個數組中的最大數字,但它一直返回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