JavaScript有7种原始类型(string、number、boolean、null、undefined、symbol、bigint)和1种引用类型,检测需综合typeof、instanceof、Object.prototype.toString.call()及专用方法如Array.isArray()。

JavaScript 有 7 种原始类型(primitive types)和 1 种引用类型(object type),其中 function 是对象的特殊子类型,Array、Date、RegExp 等也属于对象,但有各自特性。检测方式需结合 typeof、instanceof、Object.prototype.toString.call() 和 Array.isArray() 等方法,不能只靠一种。
7 种原始类型及 typeof 检测结果
原始类型包括:string、number、boolean、null、undefined、symbol(ES6)、bigint(ES2020)。它们是不可变的、按值传递的。
-
typeof "hello"→"string" -
typeof 42→"number" -
typeof true→"boolean" -
typeof undefined→"undefined" -
typeof Symbol("id")→"symbol" -
typeof 123n→"bigint" -
typeof null→"object"(这是历史 bug,需单独判断)
引用类型与 typeof 的局限性
typeof 对所有对象(包括数组、日期、正则、普通对象)都返回 "object",对函数返回 "function"(这是例外)。因此它无法区分不同对象类型。
-
typeof []→"object"(不是 "array") -
typeof new Date()→"object" -
typeof /abc/→"object"(某些环境可能返回 "regexp",但不标准) -
typeof function() {}→"function" -
typeof null→"object"(再次强调:必须额外用val === null判断)
准确识别对象子类型的推荐方法
使用 Object.prototype.toString.call() 是最可靠的标准方式,它会返回形如 "[object Array]" 的字符串。
技术上面应用了三层结构,AJAX框架,URL重写等基础的开发。并用了动软的代码生成器及数据访问类,加进了一些自己用到的小功能,算是整理了一些自己的操作类。系统设计上面说不出用什么模式,大体设计是后台分两级分类,设置好一级之后,再设置二级并选择栏目类型,如内容,列表,上传文件,新窗口等。这样就可以生成无限多个二级分类,也就是网站栏目。对于扩展性来说,如果有新的需求可以直接加一个栏目类型并新加功能操作
立即学习“Java免费学习笔记(深入)”;
-
Object.prototype.toString.call([])→"[object Array]" -
Object.prototype.toString.call(new Date())→"[object Date]" -
Object.prototype.toString.call(/abc/)→"[object RegExp]" -
Object.prototype.toString.call({})→"[object Object]" -
Object.prototype.toString.call(null)→"[object Null]" -
Object.prototype.toString.call(undefined)→"[object Undefined]"
可封装为工具函数:
function getType(val) {
return Object.prototype.toString.call(val).slice(8, -1).toLowerCase();
}
// getType([]) → "array"
// getType(new Date()) → "date"
特殊情况的检测建议
部分类型有更简洁、语义明确的专用方法,优先使用:
- 数组:用
Array.isArray(arr)(比toString更快、更直接) - 函数:用
typeof fn === "function"(兼容性好,且能覆盖箭头函数等) - NaN:用
Number.isNaN(val)(避免isNaN("abc")返回 true 的问题) - 有限数字:用
Number.isFinite(val)(排除Infinity和NaN) - 空值判断:分开检查
val === null和val === undefined,或用val == null(仅当允许隐式转换时)









