根据MDN
如果参数不能转换为数字,则返回
NaN
有些人可以解释原因Number('')并Number(null)返回,0因为没有有效的数字。
首先我认为这可能是因为它们是错误的值。但后来我发现Number(undefined)不返回0。
console.log(Number(undefined)); //NaN
console.log(Number(null)); //0
console.log(Number('')); //0Run Code Online (Sandbox Code Playgroud)
纯粹是因为规范是这样说的,在这里并链接到这里。据我所知,没有比这更深层的逻辑了。那里的第二个链接显示了Number(当作为函数调用时)根据输入类型执行的操作:
- 未定义 => 返回 NaN。
- 空 => 返回 +0。
- Boolean => 如果参数为真,则返回 1。如果参数为假,则返回 +0。
- 数字 => 返回参数(无转换)。
- 字符串 => 请参阅下面的语法和转换算法。
- Symbol => 抛出 TypeError 异常。
- 对象 => 应用以下步骤:
- 让 primValue 是?ToPrimitive(参数,提示编号)。
- 返回 ?ToNumber(primValue)。
“下面的语法和转换算法”说,除其他外:
StringNumericLiteral ::: [empty] 的 MV [数学值] 为 0。
| 归档时间: |
|
| 查看次数: |
57 次 |
| 最近记录: |