JavaScript中判断数据类型的几种方法

1. typeof

1.1 用法

1
2
3
4
5
typeof '123' // string
typeof undefined // undefined
typeof function () {
return 1;
} // function

1.1 缺陷

判断数组,对象,null都返回object

1
2
3
typeof [] // object
typeof {} // object
typeof null // object

2. instanceof

2.1 用法

instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。

1
2
3
4
5
var arr = [1, 2, 3];
arr instanceof Array // true

var obj = {};
obj instanceof Array // false

2.1 缺陷

可以区分引用类型,但是无法区分基本数据类型

1
2
var num = 1;
num instanceof Number // false

instanceof判断数组时结果失真,所以应该先判断数组类型,然后再去判断对象类型。如果先判断对象,那么数组值也会被判断为对象类型,这无法满足要求。

1
2
3
4
5
6
7
var a = [1, 2, 3];
console.log(a instanceof Array); // true
console.log(a instanceof Object); // true

var b = { name: 'kingx' };
console.log(b instanceof Array); // false
console.log(b instanceof Object); // true

3. constructor(判断构造函数)

判断一个变量是否是数组或者对象,从另一个层面讲,就是判断变量的构造函数是Array类型还是Object类型。因为一个对象的实例都是通过构造函数生成的,所以,我们可以直接判断一个变量的constructor属性。

3.1 用法

constructor 在其对应对象的原型下面,是自动生成的。

当我们写一个构造函数的时候,程序会自动添加:构造函数名.prototype.constructor = 构造函数名

1
2
3
4
5
6
7
8
var arr = '123';
arr.constructor === String // true

var arr = [1, 2, 3];
arr.constructor === Array // true

var obj = {};
obj.constructor == Object // true

3.1 缺陷

不能判断undefined和null的类型,因为null和undefined是无效的对象,因此是不会有constructor存在的

1
2
3
4
5
var arr = undefined;
console.log(arr.constructor === Undefined) // Cannot read property 'constructor' of undefined

var obj = null;
console.log(obj.constructor === Null) // Cannot read property 'constructor' of undefined

4. toString()

4.1 用法

可以检测出所有的类型

1
2
3
var str = 'hello';
console.log(Object.prototype.toString.call(str)); //[object String]
console.log(Object.prototype.toString.call(str) === '[object String]'); // true

4.1 缺陷

IE6下,undefined和null均为Object

总结一下

方法 用法 缺陷
typeof typeof ‘123’ // string 数组、对象、null都返回object
instanceof [1, 2, 3] instanceof Array // true 无法用来判断基本数据类型;[] instanceof Object同样返回true
constructor [].constructor === Array // true 无法判断undefined和null
toString Object.prototype.toString.call({}) === ‘[object Object]’ 无,可以检测所有类型

JavaScript中判断数据类型的几种方法
https://xypecho.github.io/2020/03/11/JavaScript中判断数据类型的几种方法/
作者
很青的青蛙
发布于
2020年3月11日
许可协议