0
How can I avoid nan?
Array.prototype.exe=()=>{ return(Math.max(this)); } let arr =[3,6,9]; console.log(arr.exe());
3 Answers
+ 1
Please refrain from inputting code like this.
The problem is, that you don't apply Math.max to the elements of the arraa, but the array itself, which is not a number.
There are two ways to solve this:
ES6+:
Array.prototype.exe = function() {
return Math.max(...this);
};
Pre-ES6:
Array.prototype.exe = function() {
return Math.max.apply(this, this);
};
0
you check if the 'number' you have currently is NaN with the method isNaN
since NaN mostly occurs from user input you just alert that the input is invalid and return out of the function