js基础之数据类型

87 阅读1分钟

一.js中的数据类型

js中的数据类型分为原始数据类型和引用数据类型
原始数据类型有:undefined null string number boolean
引用数据类型有:object function array 

二.js中检测数据类型的方法

typeof(要检测的值) 
返回值有:number string boolean undefined object function
注意:typeof检测null的时候返回值是object
    这是因为typeof去检测类型的时候是根据检测机器码后三位是000的时候会返回一个objectnull全部是0
注意:typeof检测方法和Array时会返回function类型。
    这是因为object定义了一个内部方法[[call]],首先判断这个引用类型有没有这个方法,有则返回function 
    
 要检测的值 instanceof 检测的数据类型
 返回值有:true false
 A instanceof B :检测A是否是由B对象实例化的,instanceof检测是根据原型链来的

三.typeof和instanceof的区别

1)返回值不一样,typeof返回的是具体的类型,instanceof返回的是ture和false2typeof可以检测任何一个数据,instanceof检测的是A是不是B的实例 

四.小技巧之如何判断是对象还是数组

typeofinstanceof都无法判断一个数据是对象还是数组 
可以使用Object.prototype.toString.call('1')   //String
        Object.prototype.toString.call([])   //Array 
        Object.prototype.toString.call({})   //Object
        Object.prototype.toString.call(null)   //Null
        Object.prototype.toString.call(undefined)   //Undefined
        Object.prototype.toString.call(new Date())   //Date
        Object.prototype.toString.call(true)   //Boolean 

五.例子

typeof:
       console.log(typeof(123))   //number
       console.log(typeof(true))  //boolean
       console.log(typeof('1111'))  //string
       console.log(typeof(undefined))   //undefined
       console.log(typeof(null))     //object
       console.log(typeof([]))       //object
       console.log(typeof(new Date()))   //object
       console.log(typeof({}))  //object
       console.log(typeof(function(){}))   //function
       console.log(typeof(Array))   //function 
instanceof:
       console.log([] instanceof Array)  //true
       console.log({} instanceof Object)  //true
       console.log(new Date() instanceof Date)  //true 
       function Person(){}
       console.log(new Person instanceof Person)  //true
       console.log([] instanceof Object)  //true 
       console.log(new Date() instanceof Object)  //true
       console.log(new Person() instanceof Object)  //true