2

有人可以解释为什么typeof的行为方式如下:

typeof 
//Returns: SyntaxError: Unexpected token } (Quite obvious)

"Why am I a " + typeof 
//Returns: SyntaxError: Unexpected token }

"Why am I a " + typeof + ""; 
//Returns: "Why am I a number"

"Why am I a " + typeof + "??"; 
//Returns: "Why am I a number"
4

2 回答 2

6

typeof 不是函数而是一元运算符,所以

typeof + ""; 

是相同的

typeof (+ "");

并将+something转换something一元 + 运算符上 EcmaScript 规范中精确的数字:

一元 + 运算符将其操作数转换为 Number 类型。

于 2013-03-29T10:33:31.783 回答
4

+"..."实际上会将字符串解析为数字。这将导致typeof + ""返回“数字”,即使返回的数字是NaN

前两种用法是完全错误的,因为typeof需要右手边。

参考:

于 2013-03-29T10:32:59.637 回答