The ECMAScript spec (5.1) defines isFinite
to act as such:
isFinite (number)
Returns false if the argument coerces to NaN, +∞, or ?∞, and otherwise returns true.
If ToNumber(number) is NaN, +∞, or ?∞, return false.
Otherwise, return true.
In other words, isFinite
is calling ToNumber on whatever's passed in, and then comparing it to either pos/neg infinity or NaN.
In JavaScript (note the use of !=
instead of the more common !==
, causing the type cast):
function isFinite(someInput) {
return !isNaN(someInput) &&
someInput != Number.POSITIVE_INFINITY &&
someInput != Number.NEGATIVE_INFINITY;
}
(As noted in the comments below, someInput != NaN
is not needed, as NaN
is defined to not be equivalent to everything, including itself.)
Now, why is null
converted to zero (as opposed to undefined
)? As TylerH says in the comments, null
means that a value exists, but is empty. The mathematical representation of this is 0. undefined
means that there isn't a value there, so we get NaN
when trying to call ToNumber
on it.
http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.2.5
However, ECMAScript 6 is bringing along a non-converting isFinite
as a property of Number
. Douglas Crockford suggested it here: http://wiki.ecmascript.org/doku.php?id=harmony:number.isfinite
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…