js中检测数据类型的四种方法

前言

先说一下JavaScript中的数据类型有哪几类?
主要分类两大类型,基本类型和引用类型。

1.typeof

先看一下用法:

console.log(typeof "");console.log(typeof 1);console.log(typeof true);console.log(typeof null);console.log(typeof undefined);console.log(typeof []);console.log(typeof function(){});console.log(typeof {});

输出结果如下:
string
number
boolean
object
undefined
object
function
object

小结

typeof可以用于检测基本类型,但碰到引用类型均返回为object。

2.instanceof

看一下用法:

console.log("1" instanceof String);console.log(1 instanceof Number);console.log(true instanceof Boolean);console.log([] instanceof Array);console.log(function(){} instanceof Function);console.log({} instanceof Object);

输出结果如下:
false
false
false
true
true
true

小结

不难看出,instanceof可以用于引用类型的检测,但对于基本类型是不生效的,另外,不能用于检测null和undefined。

3.constructor

先看一下用法:

console.log(("1").constructor === String);console.log((1).constructor === Number);console.log((true).constructor === Boolean);console.log(([]).constructor === Array);console.log((function() {}).constructor === Function);console.log(({}).constructor === Object);

输出结果:
true
true
true
true
true
true

撇去null和undefined,似乎说constructor能用于检测js的基本类型和引用类型。但当涉及到原型和继承的时候,便出现了问题,如下:

function fun() {};fun.prototype = new Array();let f = new fun();console.log(f.constructor===fun);console.log(f.constructor===Array);

在这里,我们先是定义了一个函数fun,并将该函数的原型指向了数组,同时,声明了一个f为fun的类型,然后利用constructor进行检测时,结果如下:
false
true

小结

撇去null和undefined,constructor能用于检测js的基本类型和引用类型,但当对象的原型更改之后,constructor便失效了。

4.Object.prototype.toString.call()

用法:

var test = Object.prototype.toString;console.log(test.call("str"));console.log(test.call(1));console.log(test.call(true));console.log(test.call(null));console.log(test.call(undefined));console.log(test.call([]));console.log(test.call(function() {}));console.log(test.call({}));

结果:
[object String]
[object Number]
[object Boolean]
[object Null]
[object Undefined]
[object Array]
[object Function]
[object Object]

这样一看,似乎能满足js的所有数据类型,那我们看下继承之后是否能检测出来

function fun() {};fun.prototype = new Array();let f = new fun();console.log(Object.prototype.toString.call(fun))console.log(Object.prototype.toString.call(f))

结果:
[object Function]
[object Object]

小结

可以看出,Object.prototype.toString.call()可用于检测js所有的数据类型。