让我们尝试在控制台中键入以下代码:
typeof + ''
这个返回“number”,而没有参数的typeof会抛出一个错误。为什么呢?
让我们尝试在控制台中键入以下代码:
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
typeof(+'')
,而不是 (typeof) + ('')
。+''
解释为0
,因此:
typeof + ''
将输出“number”
回答你的第二个问题,typeof
需要一个参数,因此如果你单独调用它,它会抛出一个错误,同样的情况也适用于调用if
。
+
不被解释为加法或连接运算符的原因是因为typeof
本身是一个一元运算符,而不是一个函数:http://es5.github.com/#x11.4.3。将+
视为一元加号是使此表达式有效的唯一方法。 - Felix Kling