痴货 阅读(6) 评论(0)

js中有六种数据类型,包括五种基本数据类型(Number,String,Boolean,Undefined,Null),和一种复杂数据类型(Object)。

typeof

由于js中的变量是松散类型的,所以它提供了一种检测当前变量的数据类型的方法,也就是typeof关键字.

    console.log(typeof   123)   //number
    console.log(typeof   'abc')  //string
    console.log(typeof    true)       //boolean
    console.log(typeof    undefined)   //undefined
    console.log(typeof new String())   //object
    console.log(typeof new Number())   //object
    console.log(typeof    null)        //object
    console.log(typeof    {})           //object
    console.log(typeof    [])           //object
    console.log(typeof   console.log)       //function

可以看到 typeof 在对复杂类型进行判断统一都是object类型的

 toString方法可以获得复杂对象类型更加详细的信息

var toString = {}.toString
console.log(toString.call(new Date))     //[object Date]
console.log(toString.call([]))                //[object Array]
console.log(toString.call({}))               //[object Object]

 

封装函数

var toString = {}.toString
    var types = {"[object Boolean]":"boolean","[object Number]":"number","[object String]":"string","[object Function]":"function","[object Array]":"array","[object Date]":"date","[object RegExp]":"regexp","[object Object]":"object","[object Error]":"error"}
    function getType( obj ) {
        //如果为null 或者 undefined 直接返回 'null','undefined'
        if ( obj == null ) {
            console.log(1,obj)
            return String( obj );
        }
        //如果是复杂对象类型或者函数类型
        if(typeof obj === "object" || typeof obj === "function"){
            return types[ toString.call(obj) ] || "object"
            //如果是基本类型
        }else {
            return typeof obj
        }
    }

    console.log(getType(123))       //number
    console.log(getType('abc'))     //string
    console.log(getType(true))      //boolean
    console.log(getType(new String()))  //string
    console.log(getType(new Number()))  //number
    console.log(getType(undefined))     //undefined
    console.log(getType(null))          //null
    console.log(getType({}))            //object
    console.log(getType([]))            //array
    console.log(getType(console.log))   //function