Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The following are examples that make sense to me.

isFinite(5) // true - makes sense to me, it is a number and it is finite
  typeof 5 // "number"
isFinite(Infinity) // false - makes sense for logical reasons
  typeof Infinity // "number"
isFinite(document) // false - makes sense as well, it's not even a number
  typeof document // "object"

The following is where I get confused.

isFinite(null) // true - Wait what? Other non-number objects returned false. I see no reason?
  typeof null // "object"

I just don't see the reasoning behind this. What I'd like is the most low-level answer possible. I think null is being converted to 0, why? What other impacts does this have?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
241 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...