判断各种数据类型的方法总结

1.typeof 

type of  ...判断数据类型

number返回number

string返回string

boolean返回boolean

undefined返回undefined

null返回object

function返回function

object返回object

array返回object

NAN返回number

2.instanceof

检查某对象是否属于某类型

instanceof是通过原型链来检查类型的,所以适用于任何”object”的类型检查。

 

 3.toString

     

     var   gettype = Object.prototype.toString

        gettype.call('aaaa')        输出      [object String]

        gettype.call(2222)         输出      [object Number]

        gettype.call(true)          输出      [object Boolean]

        gettype.call(undefined)  输出      [object Undefined]

        gettype.call(null)                  输出   [object Null]

         gettype.call({})                   输出   [object Object]

         gettype.call([])                    输出   [object Array]

         gettype.call(function(){})     输出   [object Function]

 

    4. constructor也能判断数据类型:

     如:    

 ''.constructor==String    

 [].constructor==Array

 var obj= new Object()   obj.constructor==Object

检查所有数据类型的方法

 

function checkType (obj) {
     return Object.prototype.toString.call(obj).slice(8,-1)
}    

 

类型检测总结

==typeof==只能检测基本数据类型,对于null还有Bug;
==instanceof==适用于检测对象,它是基于原型链运作的;
==constructor==指向的是最初创建者,而且容易伪造,不适合做类型判断;
==Object.prototype.toString==适用于ECMA内置JavaScript类型(包括基本数据类型和内置对象)的类型判断;
基于引用判等的类型检查都有跨窗口问题,比如instanceof和constructor。
总之,如果你要判断的是基本数据类型或JavaScript内置对象,使用toString; 如果要判断的时自定义类型,请使用instanceof。

posted @ 2020-02-17 17:11  短腿~欧尼  阅读(770)  评论(0编辑  收藏  举报