javaScript判断数据类型的方法

90 阅读1分钟

一、简单数据类型

1、typeof
    =>语法:typeof 数据
    =>作用: 判断一些简单数据类型
    =>返回值: 字符串
    =>例子:    
        //判别基本数据类型(除了null外)
        typeof undefined;  //'undefined'
        typeof 7;  //'number'
        typeof '7';  //'string'
        typeof true;  //'boolean'
        typeof Symbol();  //'symbol'
        typeof 5n // 'bigint'
        typeof null;  //'object'

        //除方法外,无法判断其他复杂数据类型
        typeof function(){};  //'function'
        typeof [];  //'object'
        typeof {};  //'object'
        typeof new Date());  //'object'

二、复杂数据类型

1、constructor
    =>语法:复杂数据类型.constructor
    =>作用: 判断复杂数据类型 
    =>返回值: 方法
    =>例子:       
        [].constructor === Array; //true 
        (function(){}).constructor === Function; //true 
        new Date().constructor === Date; //true
        {}.constructor  //报错:Uncaught SyntaxError: Unexpected token '.'
2、instanceof
    => 语法:复杂数据类型 instanceof 原始构造函数
    => 作用: 判断复杂数据类型 
    => 返回值: 字符串
    => 例子:
         [] instanceof Array;//true 
         (function(){}) instanceof Function; //true 
         new Date() instanceof Date; //true
3、toString
    => 语法:Object.prototype.toString.call(复杂数类型)
    => 作用: 万能型选手 
    => 返回值: 字符串 
        ->'[object 类型]'
    => 例子:
        Object.prototype.toString.call('7')   // '[object String]' 
        Object.prototype.toString.call(7)  // '[object Number]' 
        Object.prototype.toString.call(["我是数组"])  // '[object Array]' 
        Object.prototype.toString.call({content:"我是对象"})  //'[object Object]'
        Object.prototype.toString.call(true)  // '[object Boolean]' 
        Object.prototype.toString.call(undefined)  // '[object Undefined]' 
        Object.prototype.toString.call(null)  // '[object Null]' 
        Object.prototype.toString.call(new Function());  // '[object Function]' 
        Object.prototype.toString.call(new Date());  // '[object Date]'
        Object.prototype.toString.call(new RegExp());  // '[object RegExp]' 
        Object.prototype.toString.call(new Error());  // '[object Error]'

三、总结:

1、typeof 适合部分基本类型和function类型的检测,无法判断null与部分复杂数据类型。

2、instanceof、constructor,并不是万能,无法判别基本数据类型,只能判别复杂数据类型,(null,undefine,string,boolean,symbol等),且也不能跨iframe使用。

3、tostring能判断所有类型,万能型方法。

参考文章:
链接:juejin.cn/post/684490…
链接:juejin.cn/post/691980…