答案:JavaScript中常用类型判断方法有typeof、instanceof、Object.prototype.toString.call()和constructor。typeof适用于基本类型但对null和引用类型不准确;instanceof可识别具体对象类型但仅限对象且跨iframe可能出错;Object.prototype.toString.call()最精确,能识别所有内置类型;constructor属性可被修改,可靠性较低。推荐优先使用typeof判断基础类型,用Object.prototype.toString.call()进行精确判断。
JavaScript 中判断数据类型有多种方法,每种方法适用场景不同,各有优劣。下面介绍几种常用方式。
1. typeof 操作符
typeof 是最常用的类型检测方法,适合判断基本数据类型。
优点:语法简单,性能好。缺点:对 null 和引用类型(如数组、日期)判断不准确。
常见返回值:
-
typeof "hello"→ "string" -
typeof 123→ "number" -
typeof true→ "boolean" -
typeof undefined→ "undefined" -
typeof function(){}→ "function" -
typeof null→ "object" (这是历史遗留问题) -
typeof []→ "object"
2. instanceof 操作符
instanceof 用于判断对象是否是某个构造函数的实例,适用于复杂数据类型。
优点:可以识别数组、日期、正则等具体对象类型。缺点:只适用于对象,对基本类型无效;跨 iframe 时可能出错。
示例:
-
[] instanceof Array→ true -
new Date() instanceof Date→ true -
/abc/ instanceof RegExp→ true
3. Object.prototype.toString.call()
这是最准确的类型判断方法,能精确识别所有内置类型。
原理:调用对象的 toString 方法,返回格式为 "[object Type]"。示例:
-
Object.prototype.toString.call([])→ "[object Array]" -
Object.prototype.toString.call(new Date())→ "[object Date]" -
Object.prototype.toString.call(null)→ "[object Null]" -
Object.prototype.toString.call("abc")→ "[object String]"
可以通过封装提取类型名:
function getType(value) { return Object.prototype.toString.call(value).slice(8, -1).toLowerCase(); }
4. c
onstructor 属性
通过对象的 constructor 属性判断其构造函数。
注意:该属性可被修改,可靠性不如 toString。示例:
-
[].constructor === Array→ true -
(new Date()).constructor === Date→ true
基本上就这些。日常推荐优先使用 typeof 判断基础类型,用 Object.prototype.toString.call() 做精确判断。不复杂但容易忽略细节。

onstructor 属性






