为什么是'null + 1 = 1'但却是'undefined + 1 = NaN'? [英] Why is `null + 1 = 1` but `undefined + 1 = NaN`?
问题描述
null + 1 = 1
undefined + 1 = NaN
我不明白这背后的逻辑是什么.都不应该都返回相同的结果吗?
I am not able to understand what is the logic behind this. Shouldn't both have returned same result?
推荐答案
基本上,因为这就是语言规范所说的内容-查看 ToNumber
:
Basically, because that's what the language spec says - looking at ToNumber
:
Type Result
Null +0
Undefined NaN
NaN
和任何东西都是NaN
从语言的角度来看,该可能有意义:null
表示显式的空值,而undefined表示未知的值.以某种方式-零是数字空值",因为它对加法是中性的.话虽如此-这是一个很大的延伸,我认为这通常是不好的设计.在真实的JavaScript代码中-您几乎永远不会在事物中添加null
.
This might make some sense from the language perspective: null
means an explicit empty value whereas undefined implies an unknown value. In some way - zero is the "number empty value" since it is neutral to addition. That said - that's quite a stretch and I think this is generally bad design. In real JavaScript code - you almost never add null
to things.
这篇关于为什么是'null + 1 = 1'但却是'undefined + 1 = NaN'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!