在javascript中typeof的行为

时间:2013-03-29 10:30:36

标签: javascript typeof

有人可以解释为什么 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"

2 个答案:

答案 0 :(得分:6)

typeof isn't a function but a unary operator,所以

typeof + ""; 

相同
typeof (+ "");

+somethingsomething转换为EcmaScript norm on the unary + operator中预先设定的数字:

  

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

答案 1 :(得分:3)

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

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

参考文献: