为什么`isFinite(null)=== true`? [英] Why does `isFinite(null) === true`?

查看:45
本文介绍了为什么`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"

我只是看不到背后的原因.我想要的是最底层的答案.我认为 null 被转换为0,为什么?这还会有什么其他影响?

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?

推荐答案

ECMAScript规范(5.1)定义了 isFinite 这样的功能:

The ECMAScript spec (5.1) defines isFinite to act as such:

isFinite(数字)

isFinite (number)

如果参数强制为NaN,+∞或-∞,则返回false,否则返回true.

Returns false if the argument coerces to NaN, +∞, or −∞, and otherwise returns true.

如果ToNumber(number)为NaN,+∞或-∞,则返回false.

If ToNumber(number) is NaN, +∞, or −∞, return false.

否则,返回true.

换句话说, isFinite 正在呼叫 ToNumber ,然后将其与pos/neg无限或NaN进行比较.

In other words, isFinite is calling ToNumber on whatever's passed in, and then comparing it to either pos/neg infinity or NaN.

在JavaScript中(请注意使用!= 而不是更常见的!== ,从而导致类型转换):

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;
}

(如下面的评论中所述, someInput!=不需要NaN ,因为 NaN 被定义为不等同于所有事物,包括其自身.)

(As noted in the comments below, someInput != NaN is not needed, as NaN is defined to not be equivalent to everything, including itself.)

现在,为什么将 null 转换为零(与 undefined 相对)?正如 TylerH在评论中说 null 的意思是值存在,但为空.其数学表示为0. undefined 表示那里没有值,因此当尝试在其上调用 ToNumber 时,得到 NaN 它.

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

但是,ECMAScript 6带来了一个不可转换的 isFinite 作为 Number 的属性.道格拉斯·克罗克福德(Douglas Crockford)在这里提出了建议: http://wiki.ecmascript.org/doku.php?id = harmony:number.isfinite

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

这篇关于为什么`isFinite(null)=== true`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆