javascript - 为什么 "typeof + ' '"returns '号'?

标签 javascript

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

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/

相关文章:

javascript - 在哪里编码以覆盖 backbone.sync

javascript - 语法错误 : Unexpected token <

javascript - 使用链接更改页面部分

javascript - 模态弹出窗口,表单无边框

javascript - 具有已知偏移量且没有夏令时的已知位置的时间

javascript - ExtJS 4 - 如果自定义验证失败,如何将表单字段标记为无效并在其周围显示红色边框(ExtJS 默认完成)?

javascript - 迭代 JSON 以创建 innerHTML 链接

javascript - 使用 javascript oop 减少代码重复

javascript - 进度回调在 jquery-file-upload 插件中始终显示 100% 上传

javascript - 以横向格式打印