JS数据类型检测

176 阅读2分钟

JS数据类型检测

[TOC]

Ref:

  • https://blog.csdn.net/zl_jay/article/details/38556829
  • https://harttle.land/2015/09/18/js-type-checking.html

JavaScript中如何检测数据类型?有四种检测的方式:

    1. typeof:检测数据类型的运算符
    1. instanceof : 检测某个实例是否属于这个类(什么是类)
    1. constructor: 获取当前实例的构造器
    1. Object.prototype.toString.call :获取当前实例的所属类信息(最常用,最好用也是最难理解的)

1. typeof

使用typeof检测,返回的结果是一个字符串,字符串中包含的内容证明了值是属于什么类型的。

1.1检测基本数据类型

【局限性1】typeof null的结果不是"null",而是"object";因为null虽然是单独的一个数据类型,但是它原本的意思是空对象指针,浏览器使用typeof检测的时候会把它按照对象来检测

typeof 12 			//=>"number"
typeof 'HelloWorld' 		//=>"string"
typeof true			//=>"boolean"
typeof null			//=>"object"
typeof undefined 		//=>"undefined"

1.2检测引用数据类型

【局限性2】使用typeof无法具体细分出到底是数组还是正则,因为返回的结果都是'object'

typeof {name:'zhangSan'}	//=>"object"
typeof function(){} 		//=>"function"
typeof []			//=>"object"
typeof /^$/			//=>"object"

1.3练习题:

问代码 `console.log(typeof typeof []);` 的输出结果是什么?

问题分析:
typeof []//->"object"
typeof "object"->"string"
typeof检测的结果首先是个字符串,所有无论写多少个typeof结果肯定是字符串'string'

2. instanceof

用于判断一个对象是否为某一数据类型,或一个变量是否为一个对象的实例

let d = [1,2,3];
let e = new Date();
let f = function(){ alert('jason'); };
console.log(d instanceof Array);        //true
console.log(e instanceof Date);            //true
console.log(f instanceof Function);        //true

3. constructor

console.log(d.constructor === Array);		//true
console.log(e.constructor === Date);		//true
console.log(f.constructor === Function);	//true

3.1 注意constructor在类继承时会出错:

function A(){};
function B(){};
var aObj = new A();
console.log(aObj.constructor === A);    //true;
console.log(aObj.constructor === B);    //false;

function C(){};
function D(){};
C.prototype = new D(); //C继承自D
var cObj = new C();
console.log(cObj.constructor === C);    //false;
console.log(cObj.constructor === D);    //true;

3.2 而instanceof方法不会出现该问题,对象直接继承和间接继承的都会报true:

console.log(cObj instanceof C);            //true
console.log(cObj instanceof D);            //true

3.3 解决construtor的问题通常是让对象的constructor手动指向自己:

cObj.constructor=C;      //将自己的类赋值给对象的constructor属性
console.log(cObj.constructor === C);    //true;
console.log(cObj.constructor === D);    //false; 基类不会报true了;

4. Object.prototype.toString.call

console.log(Object.prototype.toString.call('Hello') === '[object String]');        //true
console.log(Object.prototype.toString.call(NaN) === '[object Number]');        //true
console.log(Object.prototype.toString.call(false) === '[object Boolean]');        //true
console.log(Object.prototype.toString.call(null) === '[object Null]');        //true
console.log(Object.prototype.toString.call(undefined) === '[object Undefined]'); //true
console.log(Object.prototype.toString.call(d) === '[object Array]');        //true
console.log(Object.prototype.toString.call(e) === '[object Date]');            //true
console.log(Object.prototype.toString.call(f) === '[object Function]');        //true