Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

javascript - Why does `isFinite(null) === true`?

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...