最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

behaviour of typeof in javascript - Stack Overflow

programmeradmin0浏览0评论

Can someone explain why typeof behaves in the following way:

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"

Can someone explain why typeof behaves in the following way:

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"
Share Improve this question asked Mar 29, 2013 at 10:30 gopi1410gopi1410 6,62510 gold badges43 silver badges76 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

typeof isn't a function but a unary operator, so

typeof + ""; 

is the same as

typeof (+ "");

and +something converts the something to a number as is precised in EcmaScript norm on the unary + operator :

The unary + operator converts its operand to Number type.

+"..." will actually parse the string as a number. This will result in typeof + "" returning "number", even though the returned number is NaN.

The first two usages are simply wrong, since typeof needs a right hand side.

References:

  • typeof operator
  • Unary + operator
发布评论

评论列表(0)

  1. 暂无评论