typeof的用法

本文最后更新于:2023年1月12日 下午

前言

typeof 的一般操作,就是用来判断某个变量是什么类型,从而进行下一步操作。但是最近发现lodash源码中typeof还有如此作用,特记录于此

常规操作

常规操作无非就是判断类型,如下

1
2
3
4
5
6
7
8
9
10
typeof null === 'object' //true 注:特殊
typeof undefined === 'undefined' //true
typeof 111 === 'number' //true
typeof '字符串' === 'string' //true
typeof true === 'boolean' //true
typeof Symbol('foo') === 'symbol' //true
typeof 111n === 'bigint' //true
typeof {} === 'object' //true
typeof [] === 'object' //true
typeof (() => {}) === 'function' //true

非常规操作

我们知道,对于未声明的变量,只能执行一个操作,那就是使用typeof判断类型

1
2
3
//let a = 1  //确保a没有声明
typeof a //undefined
console.log(a) //报错: Uncaught ReferenceError: a is not defined

那怎么能让第二个语句不报错,有输出呢?往下看

1
console.log(typeof a !== 'undefined' && a) //输出false

lodash类似源码

1
2
3
4
/** Detect free variable `global` from Node.js. */
const freeGlobal = typeof global === 'object' && global !== null && global.Object === Object && global

export default freeGlobal

typeof的用法
https://www.yxlazy.xyz/2021/06/30/typeof的用法/
作者
yxlazy
发布于
2021年6月30日
更新于
2023年1月12日
许可协议