javascript 数据类型判断

1. typeof

typeof返回值为字符串,有六种类型

number,string,boolean,function,undefined,object,

typeof通常用来区分undefined和function类型,无法分辨复杂类型,例如array类型,和plain object类型

用 typeof(reValue) === "undefined" 来区分undefined,不用 reValue === undefined 来区分undefined,是因为reValue未声明时,浏览器直接报错

用typeof(reValue) === "function" 来检测function

typeof可以区分基本类型,函数类型,其他的具体对象类型全部归为对象类型

包括 new String('abc'), new Number('123'),null,Array都会被认为是对象类型

总之,typeof只能区分基本类型和函数类型,通常用来检测undefined和function


2. instanceof

instanceof用来判断对象实例与类型的关系,返回值为bool类型,不能跨iframe。

3. constructor

constructor检测是使用对象的constructor属性,其值为该对象类型的构造函数的引用。例如,num.constructor的值为function Number(){native code}。此方法可以用来判断Array类型,例如 obj.constructor === Array 来判断其类型是否为Array。

constructor方法有一些缺点,一是constructor属性可以被修改,二是constructor的判断不能穿越iframe。


4. Object.prototype.toString.call

此方法调用具体对象,会返回字符串,共11种类型,如下

'[object Number]' '[object String]' '[object Boolean]' '[object Array]' '[object Object]'
'[object Function]' '[object Undefined]' '[object Null]' '[object Date]' '[object RegExp]' '[object Error]'

此方法是用来检测类型的终极方法,jquery的type()方法就是使用此方法来判断的,具体使用类型判断时候,可以解决$.type的实现。

Object.prototype.toStirng.call的原理

1.调用对象的toString方法,会返回其字符串形式,应为不同的类型重写了toStirng方法,例如,
Array返回逗号连接的字符串,function返回函数本身

2.调用对象的原型链上的Object的toString方法,会返回其对象类型[[class]],形式是
[object [[class]]]的一个字符串,可以得到对象的具体类型

类型判断总结

===   用来判断   null
typeof  用来判断       undefined,function,object
Object.prototype.toString.call 用来判断 array,number,boolean等具体类型

Object.prototype.toString.call在ie6上有bug,string,undefined,null类型均为Object
在ie6上可以使用typeof来判断string

数据类型判断type方法简单实现

function type(obj) {
    var class2type = {};
    'Boolean Number String Function Array Date RegExp Object Error Null Undefined'.split(' ').map((item, index) => {
        class2type['[object ' + item + ']'] = item.toLowerCase();
    });
    //object或function类型用toString判断,基本类型用typeof判断
    return typeof obj === 'object' || typeof obj === 'function' ?
        class2type[Object.prototype.toString.call(obj)] || 'object' : typeof obj;
}


参考:http://www.2cto.com/kf/201507/414817.html

原文地址:https://www.cnblogs.com/mengff/p/5004913.html