js中的数据类型

基本数据类型: Undefined、Null、Boolean、Number、String、Symbol

引用数据类型:Object

1、typeof

typeof可以识别出基本类型:boolean,number,undefined、string、symbol,也可以识别function

但是不能识别null,会把bull、array、object统一归为object。

2、instanceof

instanceof不能识别出基本的数据类型,null、undefined、boolean、number、string、symbol

可以检测出引用类型,如array、object、function,同时对于使用new声明的类型,话可以检测出多层几曾关系。如objA instanceof A 

instanceof一般用来检测对象类型,以及继承关系。

3、constructor

null、undefined没有constructor方法,因此constructor不能判断undefiend和null

但是他是不安全的,因为constructor的指向是可以改变的

4、Object.prototype.toString.call

此方法可以相对较全的判断js的数据类型。

至于再项目中使用哪个个判断,还是要看使用场景、具体的选择、一般类型可以选择typeof,引用类型可以使用instanceof

5、使用例子



console.log(typeof bool); //boolean
console.log(arr instanceof Array);// true
console.log(obj instanceof Object);// true
console.log(fun instanceof Function);// true
console.log(bool.constructor === Boolean);// true
console.log(Object.prototype.toString.call(bool));//[object Boolean]