为什么"typeof+''"返回'数字'

Why "typeof + ''" returns 'number'?

本文关键字:quot 数字 返回 为什么 typeof+      更新时间:2023-09-26

让我们尝试在控制台中键入以下代码:

typeof + ''

这将返回"number",而不带参数的typeof本身将引发错误。为什么?

一元加号运算符调用字符串上的内部ToNumber算法。+'' === 0

typeof + ''
// The `typeof` operator has the same operator precedence than the unary plus operator,
// but these are evaluated from right to left so your expression is interpreted as:
typeof (+ '')
// which evaluates to:
typeof 0
"number"

parseInt不同,+运算符调用的内部ToNumber算法将空字符串(以及仅空白字符串)计算为编号0。从ToNumber规范向下滚动一点:

空的或仅包含空白的StringNumericLiteral将转换为+0

下面是控制台上的快速检查:

>>> +''
<<< 0
>>> +' '
<<< 0
>>> +''t'r'n'
<<< 0
//parseInt with any of the strings above will return NaN

供参考:

  • 一元加号和减号运算符的重要用途是什么?(所以)
  • ES5#9.3.1适用于字符串类型的ToNumber(ES5规范)
  • 运算符优先级(MDN)

计算结果为typeof(+''),而不是(typeof) + ('')

Javascript将以下+ ''解释为0,因此:

typeof + ''将回显"数字"

为了回答第二个问题,typeof需要一个参数,所以如果你自己调用它,它会抛出一个错误,就像你自己调用if一样。