JavaScript中判断变量类型的5种方法详解

作者:木棉时间:2026-10-29 13:24:41浏览:536

本文详细解析JavaScript中判断变量类型的五种常用方法:typeof、instanceof、constructor、Object.prototype.toString.call以及jQuery的$.type。通过对比测试,分析各方法对基本类型、引用类型、null、undefined及跨iframe场景的识别能力与局限性,帮助开发者根据实际需求选择最合适的类型检测方案。

JavaScript变量类型概述

JavaScript包含5种基本数据类型:Undefined、Null、Boolean、Number和String,以及1种复杂数据类型Object。Object类型下还细分了Array、Function、Date等具体子类。本文将深入探讨如何准确判断变量的类型。

在介绍具体方法前,先定义一组涵盖常见类型的测试变量,以便后续观察各方法对变量类型的解析结果。这些变量基本覆盖了实际开发中遇到的主要类型。


var num = 123;
var str = 'abcdef';
var bool = true;
var arr = [1, 2, 3, 4];
var json = {name:'wenzi', age:25};
var func = function(){ console.log('this is function'); }
var und = undefined;
var nul = null;
var date = new Date();
var reg = /^[a-zA-Z]{5,20}$/;
var error= new Error();

方法一:使用typeof检测

1. 使用typeof检测

typeof是开发者最常用的类型检测手段。接下来,我们使用typeof对上述测试变量进行类型检测:


console.log(
	typeof num, 
	typeof str, 
	typeof bool, 
	typeof arr, 
	typeof json, 
	typeof func, 
	typeof und, 
	typeof nul, 
	typeof date, 
	typeof reg, 
	typeof error
);
// number string boolean object	object function undefined object object object object

从输出结果可见,arr、json、nul、date、reg、error均被识别为object类型,其他变量则能正确显示类型。当需要判断变量是否为number、string、boolean、function、undefined或json类型时,typeof是有效的选择。然而,对于其他类型(包括null),typeof无法准确区分。此外,typeof无法区分Array和Object,因为两者返回结果均为object。

方法二:使用instanceof检测

2. 使用instanceof检测

在JavaScript中,虽然typeof是常见的类型判断工具,但当处理引用类型时,无论对象具体属于哪种类型,typeof始终返回“object”。为此,ECMAScript引入了instanceof运算符。instanceof与typeof类似,用于识别对象类型,但不同之处在于,它要求开发者明确确认对象是否为特定类型。例如:


function Person(){

}
var Tom = new Person();
console.log(Tom instanceof Person); // true

进一步观察以下示例:


function Person(){

}
function Student(){

}
Student.prototype = new Person();
var John = new Student();
console.log(John instanceof Student); // true
console.log(John instancdof Person); // true

instanceof还能检测多层继承关系。 接下来,我们使用instance检测前述变量:


console.log(
	num instanceof Number,
	str instanceof String,
	bool instanceof Boolean,
	arr instanceof Array,
	json instanceof Object,
	func instanceof Function,
	und instanceof Object,
	nul instanceof Object,
	date instanceof Date,
	reg instanceof RegExp,
	error instanceof Error
)
// num : false 
// str : false 
// bool : false 
// arr : true 
// json : true 
// func : true 
// und : false 
// nul : false 
// date : true 
// reg : true 
// error : true

从运行结果可以看出,num、str和bool未能检测出类型。但如果采用以下方式创建num,则可以成功检测:


var num = new Number(123);
var str = new String('abcdef');
var boolean = new Boolean(true);

同时需要注意,und和nul被检测为Object类型并返回true。这是因为JavaScript中没有Undefined和Null的全局类型,它们均属于Object类型,因此检测结果为true。

方法三:使用constructor检测

3. 使用constructor检测

在使用instanceof检测变量类型时,无法识别number、'string'和bool的类型。因此,我们需要采用另一种方式来解决这一问题。 constructor原本是原型对象上的属性,指向构造函数。根据实例对象查找属性的规则,若实例对象上没有实例属性或方法,则会沿原型链向上查找。因此,实例对象也可以使用constructor属性。 我们先输出num.constructor的内容,即数字类型变量的构造函数形态:

function Number() { [native code] }

可以看到,它指向了Number的构造函数。因此,我们可以使用num.constructor==Number来判断num是否为Number类型,其他变量也采用类似方式:


function Person(){

}
var Tom = new Person();

// undefined和null没有constructor属性
console.log(
	Tom.constructor==Person,
	num.constructor==Number,
	str.constructor==String,
	bool.constructor==Boolean,
	arr.constructor==Array,
	json.constructor==Object,
	func.constructor==Function,
	date.constructor==Date,
	reg.constructor==RegExp,
	error.constructor==Error
);
// 所有结果均为true

从输出结果可以看出,除了undefined和null外,其他类型的变量均能通过constructor判断出类型。 然而,使用constructor并非绝对可靠,因为constructor属性可能被修改,从而导致检测结果不准确。例如:


function Person(){

}
function Student(){

}
Student.prototype = new Person();
var John = new Student();
console.log(John.constructor==Student); // false
console.log(John.constructor==Person); // true

方法四:使用Object.prototype.toString.call

在上述示例中,Student原型中的constructor被修改为指向Person,导致无法检测出实例对象John真实的构造函数。 此外,使用instanceof和constructor时,被判断的array必须是在当前页面声明的!例如,一个页面(父页面)包含一个框架,框架中引用了一个页面(子页面)。在子页面中声明了一个array,并将其赋值给父页面的一个变量。此时判断该变量,Array == object.constructor;会返回false。原因如下: 1、array属于引用型数据,在传递过程中,仅仅是引用地址的传递。 2、每个页面的Array原生对象所引用的地址是不一样的,在子页面声明的array,所对应的构造函数,是子页面的Array对象;父页面来进行判断,使用的Array并不等于子页面的Array;切记,不然很难跟踪问题! 4. 使用Object.prototype.toString.call

我们先不深究其原理,先来看看它如何检测变量类型:


console.log(
	Object.prototype.toString.call(num),
	Object.prototype.toString.call(str),
	Object.prototype.toString.call(bool),
	Object.prototype.toString.call(arr),
	Object.prototype.toString.call(json),
	Object.prototype.toString.call(func),
	Object.prototype.toString.call(und),
	Object.prototype.toString.call(nul),
	Object.prototype.toString.call(date),
	Object.prototype.toString.call(reg),
	Object.prototype.toString.call(error)
);
// '[object Number]' '[object String]' '[object Boolean]' '[object Array]' '[object Object]'
// '[object Function]' '[object Undefined]' '[object Null]' '[object Date]' '[object RegExp]' '[object Error]'

从输出结果来看,Object.prototype.toString.call(变量)输出的是一个字符串,字符串里有一个数组,第一个参数是Object,第二个参数就是这个变量的类型,而且,所有变量的类型都检测出来了,我们只需要取出第二个参数即可。或者可以使用Object.prototype.toString.call(arr)=="object Array"来检测变量arr是不是数组。 我们现在再来看看ECMA里是是怎么定义Object.prototype.toString.call的:

代码如下:

Object.prototype.toString( ) When the toString method is called, the following steps are taken:
1. Get the [[Class]] property of this object.
2. Compute a string value by concatenating the three strings “[object “, Result (1), and “]”.
3. Return Result (2)

方法五:jQuery中$.type的实现

上面的规范定义了Object.prototype.toString的行为:首先,取得对象的一个内部属性[[Class]],然后依据这个属性,返回一个类似于”[object Array]”的字符串作为结果(看过ECMA标准的应该都知道,[[]]用来表示语言内部用到的、外部不可直接访问的属性,称为“内部属性”)。利用这个方法,再配合call,我们可以取得任何对象的内部属性[[Class]],然后把类型检测转化为字符串比较,以达到我们的目的。 5. jquery中$.type的实现

在jquery中提供了一个$.type的接口,来让我们检测变量的类型:


console.log(
	$.type(num),
	$.type(str),
	$.type(bool),
	$.type(arr),
	$.type(json),
	$.type(func),
	$.type(und),
	$.type(nul),
	$.type(date),
	$.type(reg),
	$.type(error)
);
// number string boolean array object function undefined null date regexp error

看到输出结果,有没有一种熟悉的感觉?对,他就是上面使用Object.prototype.toString.call(变量)输出的结果的第二个参数呀。 我们这里先来对比一下上面所有方法检测出的结果,横排是使用的检测方法, 竖排是各个变量:

类型判断 typeof instanceof constructor toString.call $.type
num number false true [object Number] number
str string false true [object String] string
bool boolean false true [object Boolean] boolean
arr object true true [object Array] array
json object true true [object Object] object
func function true true [object Function] function
und undefined false - [object Undefined] undefined
nul object false - [object Null] null
date object true true [object Date] date
reg object true true [object RegExp] regexp
error object true true [object Error] error
优点 使用简单,能直接输出结果 能检测出复杂的类型 基本能检测出所有的类型 检测出所有的类型 -
缺点 检测出的类型太少 基本类型检测不出,且不能跨iframe 不能跨iframe,且constructor易被修改 IE6下undefined,null均为Object -

这样对比一下,就更能看到各个方法之间的区别了,而且Object.prototype.toString.call和$type输出的结果真的很像。我们来看看jquery(2.1.2版本)内部是怎么实现$.type方法的:


// 实例对象是能直接使用原型链上的方法的
var class2type = {};
var toString = class2type.toString;

// 省略部分代码...

type: function( obj ) {
	if ( obj == null ) {
		return obj + "";
	}
	// Support: Android<4.0, iOS<6 (functionish RegExp)
	return (typeof obj === "object" || typeof obj === "function") ?
		(class2type[ toString.call(obj) ] || "object") :
		typeof obj;
},

// 省略部分代码... 

// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
	class2type[ "[object " + name + "]" ] = name.toLowerCase();
});

我们先来看看jQuery.each的这部分:


// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
	class2type[ "[object " + name + "]" ] = name.toLowerCase();
});

//循环之后,`class2type`的值是: 
class2type = {
	'[object Boolean]' : 'boolean', 
	'[object Number]' : 'number',
	'[object String]' : 'string',
	'[object Function]': 'function',
	'[object Array]'  : 'array',
	'[object Date]'  : 'date',
	'[object RegExp]' : 'regExp',
	'[object Object]' : 'object',
	'[object Error]'  : 'error'
}

再来看看type方法:


// type的实现
type: function( obj ) {
	// 若传入的是null或undefined,则直接返回这个对象的字符串
	// 即若传入的对象obj是undefined,则返回"undefined"
	if ( obj == null ) {
		return obj + "";
	}
	// Support: Android<4.0, iOS<6 (functionish RegExp)
	// 低版本regExp返回function类型;高版本已修正,返回object类型
	// 若使用typeof检测出的obj类型是object或function,则返回class2type的值,否则返回typeof检测的类型
	return (typeof obj === "object" || typeof obj === "function") ?
		(class2type[ toString.call(obj) ] || "object") :
		typeof obj;
}

当typeof obj === "object" || typeof obj === "function"时,就返回class2type[ toString.call(obj)。到这儿,我们就应该明白为什么Object.prototype.toString.call和$.type那么像了吧,其实jquery中就是用Object.prototype.toString.call实现的,把'[object Boolean]'类型转成'boolean'类型并返回。若class2type存储的没有这个变量的类型,那就返回”object”。 除了”object”和”function”类型,其他的类型则使用typeof进行检测。即number, string, boolean类型的变量,使用typeof即可。

作者最新文章