js typeof 的魔法:原来你是这样判断类型的!
|
freeflydom
2025年6月5日 14:44
本文热度 145
|
一、typeof 的基本使用
先来个最简单的例子:
console.log(typeof 42);
console.log(typeof '我');
console.log(typeof true);
看起来很简单对吧?但如果你以为typeof
就这么点能耐,那可就太小看它了!
二、typeof 的"奇葩"表现
这里有几个容易踩坑的例子:
console.log(typeof null);
console.log(typeof []);
console.log(typeof function(){});
看到没?null
居然返回"object"
,这可是JavaScript著名的历史遗留问题!当年我在项目里就被这个坑过,debug了半天才发现是类型判断出了问题。
三、typeof 的工作原理
其实typeof
判断类型的原理很简单:
- 对于原始类型(除null外),直接返回对应类型字符串
- 对于函数,返回
"function"
- 对于其他对象(包括数组、日期等),统一返回
"object"
- 对于
null
,这是个特例,因为历史原因返回"object"
四、实战中的小技巧
在实际开发中,我经常用这样的组合判断:
function checkType(value) {
if (value === null) return 'null';
return typeof value === 'object'
? Object.prototype.toString.call(value).slice(8, -1).toLowerCase()
: typeof value;
}
console.log(checkType([]));
console.log(checkType(new Date()));
五、为什么要有typeof?
想象一下没有typeof
的世界:
if (value.constructor === String) {...}
if (value instanceof Array) {...}
typeof
提供了一种快速判断基本类型的方法,虽然不完美,但在大多数情况下已经够用了。
六、新型替代方案
现在我们有更多选择:
console.log(Array.isArray([]));
console.log(typeof 我 === 'undefined');
七、总结
typeof
是JS内置的类型判断操作符- 对原始类型判断准确(除null外)
- 对引用类型大部分返回
"object"
- 函数会返回
"function"
- 实际开发中可能需要组合其他判断方法
转自https://juejin.cn/post/7511927859772407827
该文章在 2025/6/5 14:44:16 编辑过