Reputation: 1345
In practising various JavaScript code katas, I came across this problem:
Write a function isIntArray with the below signature
function isIntArray(arr) {
return true;
}
I had made my own solution to this, but one of the accepted solutions was the following:
function isIntArray(arr) {
return Array.isArray(arr) && arr.every(function (x) { return Math.floor(x)=== x });
}
Now i understand how the Math.floor section works when determining if x is a decimal, but what i don't understand is how it doesn't fall over when it encounters something like:
var arr = [1,2,"asd",NaN,5];
I Tried reading through some guides on Math.floor and Array.prototype.every and i can't find anything that explains this. Surely if x was a string then Math.floor(x) === x should return a TypeError?
Upvotes: 2
Views: 501
Reputation: 59252
Surely if
x
was a string thenMath.floor(x) === x
should return aTypeError
?
Nope. Most mathematical functions and operations return NaN
if one of the operand cannot be converted into number and then operated upon.
So, it becomes Math.floor("asd") === "asd"
is essentially
NaN === "asd" // which is obviously false
Upvotes: 4