• 如何准确判断变量的数据类型


    在解决上面的问题之前,我们要了解下基本的知识

    JS的数据类型有五种基本类型,undefined,null,boolean,number,string。

    还有一种复杂的数据类型,object

    从储存方式看,又分为值类型,引用类型,object便是引用类型。

    typeof

    该操作符只能判断值类型的数据类型,引用类型无法具体细分

    console.log(typeof '123'); // string
    console.log(typeof 123); // number
    console.log(typeof true); // boolean
    console.log(typeof undefined); // undefined
    console.log(typeof null); // object
    console.log(typeof [1,2]); // object
    console.log(typeof {a:1});// object
    console.log(typeof /[a]/);// object
    console.log(typeof function(){}) // function
    

    上面代码中,null,数组,对象,正则表达式都是输出object,但是函数typeof分辨出来了,但并不是函数属于值类型,函数依然是对象,只是函数的地位很高,所以最开始这门语言在设计时便让typeof可以分辨出函数。

    那么问题来了,如何细分object的数据类型呢

    function judgeType(item){
      let type = typeof item;
    
      //判断元素是否为数组
      if(type === 'object'){
    
      	if(Array.isArray(item)){
      		type = 'array';
      	}else if(item == undefined){
      		type = 'null';
      	}else{
      		const temp = item.toString();
    
    	    if(temp[0] === '/'){
    	      type = 'regexp';
    	    }
      	}
        
      }
    
      return type;
    }
    

    上面的代码应该不难看懂,就不具体说明了,测试下该函数的准确性

    function judgeType(item){
      let type = typeof item;
    
      //判断元素是否为数组
      if(type === 'object'){
    
      	if(Array.isArray(item)){
      		type = 'array';
      	}else if(item == undefined){
      		type = 'null';
      	}else{
      		const temp = item.toString();
    
    	    if(temp[0] === '/'){
    	      type = 'regexp';
    	    }
      	}
        
      }
    
      return type;
    }
    
    console.log(judgeType('123'));
    console.log(judgeType(123) );
    console.log(judgeType(true) );
    console.log(judgeType(undefined) )
    console.log(judgeType(null) ) // null
    console.log(judgeType([1,2]) ); // array
    console.log(judgeType({a:1}) ); // object
    console.log(judgeType(/[a]/) ); // regexp
    console.log(judgeType(function(){}) ) 
    
    

    当然上面的函数并不能判断Set,Map等对象,输出的依然是object。

  • 相关阅读:
    js 字符串转化成数字:(实例:用正则检测大于0的正数,最多保留4位小数)
    SQL Server 2008 阻止保存要求重新创建表的更改问题的设置方法
    Entity Framework学习二:定义数据结构
    Entity Framework学习一:在.net类基础上创建新数据库
    Create Primary Key using Entity Framework Code First
    MVC缓存(转载)
    不错的博文地址
    read xml test
    xml读取类
    VS2010+ASP.NET MVC4+EF4+JqueryEasyUI+Oracle项目开发(转载)
  • 原文地址:https://www.cnblogs.com/tourey-fatty/p/12721449.html
Copyright © 2020-2023  润新知