简体   繁体   English

为什么“typeof + ''”返回'number'?

[英]Why “typeof + ''” returns 'number'?

Let's try to type code below in console:让我们尝试在控制台中键入以下代码:

typeof + ''

This returns 'number', while typeof itself without argument throws an error.这将返回 'number',而没有参数的 typeof 本身会引发错误。 Why?为什么?

The unary plus operator invokes the internal ToNumber algorithm on the string. 一元加号运算符调用字符串的内部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"

Differently from parseInt , the internal ToNumber algorithm invoked by the + operator evaluates empty strings (as well as white-space only strings) to Number 0 .parseInt不同的是, +运算符调用的内部ToNumber算法将空字符串(以及只有空格的字符串)计算为 Number 0 Scrolling down a bit from the ToNumber spec :ToNumber规范向下滚动一点:

A StringNumericLiteral that is empty or contains only white space is converted to +0 .空的或仅包含空格的StringNumericLiteral将转换为+0

Here's a quick check on the console:这是对控制台的快速检查:

>>> +''
<<< 0
>>> +' '
<<< 0
>>> +'\t\r\n'
<<< 0
//parseInt with any of the strings above will return NaN

For reference:以供参考:

计算结果为typeof(+'') ,而不是(typeof) + ('')

Javascript interprets the following + '' as 0 so : Javascript 将以下+ ''0所以:

typeof + '' will echo `number' typeof + ''将回显 `number'

To answer your second question, typeof takes an argument so if you call it by itself it will throw an error same thing if you call if by itself.要回答你的第二个问题, typeof需要一个参数,所以,如果你本身调用它,如果你把它就会抛出一个错误同样的事情, if本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM