为什么 "typeof + ''" 返回 'number'?

5

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

typeof + ''

这个返回“number”,而没有参数的typeof会抛出一个错误。为什么呢?


2
由于一元加号。 - Dave Newton
https://dev59.com/SWox5IYBdhLWcg3wnlpI - Cybrix
+ 不被解释为加法或连接运算符的原因是因为 typeof 本身是一个一元运算符,而不是一个函数:http://es5.github.com/#x11.4.3。将 + 视为一元加号是使此表达式有效的唯一方法。 - Felix Kling
3个回答

7

一元正号运算符会对字符串调用内部的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

参考资料:


1
那会被评估为 typeof(+''),而不是 (typeof) + ('')

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

typeof + ''将输出“number”

回答你的第二个问题,typeof需要一个参数,因此如果你单独调用它,它会抛出一个错误,同样的情况也适用于调用if


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接