让我们尝试在控制台中键入以下代码:
typeof + ''
Run Code Online (Sandbox Code Playgroud)
这将返回'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"
Run Code Online (Sandbox Code Playgroud)
与此不同的是parseInt,运算符ToNumber调用的内部算法将+空字符串(以及仅空白字符串)计算为Number 0.从ToNumber规范中向下滚动一下:
甲StringNumericLiteral是空的或仅包含空白转换成
+0.
这是对控制台的快速检查:
>>> +''
<<< 0
>>> +' '
<<< 0
>>> +'\t\r\n'
<<< 0
//parseInt with any of the strings above will return NaN
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
185 次 |
| 最近记录: |