typeof 运算符的执行顺序
理解 typeof 的链式调用和函数返回值的类型判断
问题
下面代码的输出是什么?
console.log(typeof typeof typeof null);
console.log(typeof console.log(1));
解答
第一行代码
typeof typeof typeof null 输出 "string"。
执行过程:
typeof null返回"object"(JavaScript 的历史遗留问题,null 被视为空对象引用)typeof "object"返回"string"typeof "string"返回"string"
第二行代码
typeof console.log(1) 先输出 1,然后输出 "undefined"。
执行过程:
console.log(1)先执行,输出1console.log()没有返回值,返回undefinedtypeof undefined返回"undefined"
完整输出
string
1
undefined
关键点
typeof运算符返回的是字符串类型,所以typeof任何字符串都返回"string"typeof null返回"object"是 JavaScript 的已知 bug,但为了向后兼容一直保留console.log()没有返回值,默认返回undefined- 函数调用会先执行,再对返回值进行
typeof运算
目录