为什么我们有“不是数字” (isNan) 函数?
许多语言都有 isNaN() 函数。我问自己:为什么要检查不是一个数字?
原因是纯逻辑的还是检查不是数字比检查是数字更快?
注意这是一个纯粹的理解问题。例如,我知道我可以否定 isNaN() 来实现 isNumber() 函数。
然而,我正在寻找一个原因,为什么我们要检查而不是数字?
Many languages have an isNaN() function. I am asking myself: why check for not being a number?
Is the reason purely logical or is it faster to check for not a number instead of is a number?
Note that this is a pure question of understanding. I know that I can negate isNaN() to achieve an isNumber() function for example.
However I am searching for a reason WHY we are checking for not a number?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
Wiki 文章
因为 Not a Number 是表达式的一种特殊情况。
你不能只使用 0 或 -1 或类似的数字,因为这些数字已经有意义。
不是数字意味着计算中出现了错误,无法从中计算出有效的数字。
它与
null
的思路相同。当然,我们可以指定一个任意数值来表示null
,但这会令人困惑,并且我们会在极端情况下遇到各种奇怪的错误。Wiki Article
Because Not a Number is a special case of an expression.
You can't just use 0 or -1 or something like that because those numbers already have meanings.
Not a Number means something went awry in a calculation and a valid number cannot be computed out of it.
It's on the same line of thinking as having
null
. Sure, we could assign an arbitrary numerical value to meannull
but it would be confusing and we'd hit all sorts of weird errors on corner cases.“Not a Number”是特定浮点计算的结果。这不是关于“嘿,这个变量保存的是 120 还是“abc”?
'Not a Number' is the result of specific floating point calculations. It's not about "hey, is this variable holding 120 or "abc"?'
isThisCaseExceptional
对我来说似乎比isEverythingNormal
更合理,因为我可能会写而不是
isThisCaseExceptional
seems more reasonable to me thanisEverythingNormal
because I'm likely to writeinstead of
检查它是否不是数字,因为假设它是数字。当您期望一个数值时,NaN 是一种特殊情况,因此对我来说这样做是有意义的。毕竟,我宁愿很少检查 isNaN 也不愿频繁检查值是否 isNum 。
The check is for whether it is not a number, because the assumption is that it is a number. NaN is the exceptional case when you're expecting a numeric value, so it makes sense to me that it is done this way. I'd rather check for isNaN infrequently than check if a value isNum frequently, after all.
这是一种报告错误情况(数学上未定义或超出技术限制)的方法。
It is a way to report an error condition (mathematically undefined or outside of technical limits).
如果计算结果不能用数字表示,许多语言都有特殊的表示形式,例如 NaN 和 Inf。因此 isNaN() 检查结果是否实际上是数字或 NaN 的特殊标记。
Many languages have special representations if the result of a computation is not representable by a number, for example NaN and Inf. So isNaN() checks, if a result is actually a number or the special marker for NaN.
NaN 用于:
NaNs are used for: