让我们尝试在控制台中输入以下代码:
typeof + ''
这会返回“number”,而没有参数的 typeof 本身会抛出错误。为什么?
最佳答案
unary plus operator在字符串上调用内部 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
spec 向下滚动一点:
A StringNumericLiteral that is empty or contains only white space is converted to
+0
.
这是在控制台上的快速检查:
>>> +''
<<< 0
>>> +' '
<<< 0
>>> +'\t\r\n'
<<< 0
//parseInt with any of the strings above will return NaN
供引用:
关于javascript - 为什么 "typeof + ' '"returns '号'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15034910/