如何判断变量类型?

391 阅读2分钟

结论

1. 一般简单的使用 typeof 或 instanceof 检测(这两种检测的不完全准确)。

2. 完全准确的使用 原生js中的 Object.prototype.toString.call 或 jquery中的 $.type 检测。可判断出14种类型:

String  Number  Boolean  Undefined  Null

Object  Function  Array     Date           RegExp

Error     Math      JSON     Arguments

________________2020_05_20_更新________________________________________________________

虽然这个方法很准确了,但是仍需要配合typeof来检测是否基本类型

var aaa = new Number(1)
Object.prototype.toString.call(aaa) // "[object Number]"
typeof aaa // "object"

各种方法简介

1. typeof

    适用于判断函数,数字,字符串,布尔值和undefined。

2. instanceof

    适用于判断引用类型。

3. constructor.name

    该方式大部分情况下都可以,弊端是undefined,或者null没有constructor 而且被修改,个人不推荐使用。

var a = ''
a.constructor.name // 返回String

注意 使用instaceof和construcor,被判断的array必须是在当前页面声明的!

___________2020_05_24___更新___________

在不同页面声明的话,可以用Array.isArray()方法来判断是否数组(高程三88页)。

4. 特性判断法

function isArray(object){
    return  object && typeof object==='object' &&
            typeof object.length==='number' &&
            typeof object.splice==='function' &&
    //判断length属性是否是可枚举的 对于数组 将得到false
    !(object.propertyIsEnumerable('length'));
}

5. Object.prototype.toString.call()

function isArray(o) {
    return Object.prototype.toString.call(o) ==='[object Array]';
} 

据我所知,jQuery的内部工具、vue的内部工具,mock的内部工具,都是采用的这种方法。

5.1 jQuery

//初始化变量
class2type={}
// Populate the class2type 
mapjQuery.each("Boolean Number String Function Array Date RegExp Object Error").split(" "),
 function(i, name) {
    class2type[ "[object " + name + "]" ] = name.toLowerCase();
 }
);

然后类型判断方法:

function( obj ) {
    if ( obj == null ) {
        return String( obj );
    }
    return typeof obj === "object" || typeof obj === "function" ?
        // 返回对象中有的结果
        class2type[ core_toString.call(obj) ] || "object" :
        // 返回typeof本身可以判断的。
        typeof obj;
}

5.2 Vue

var _toString = Object.prototype.toString;
function toRawType (value) {
    return _toString.call(value).slice(8, -1)
    // 直接从第八位返回到倒数第二位
}

5.3 Mock

Util.type = function type(obj) {
    return (obj === null || obj === undefined) ? String(obj) :
        Object.prototype.toString
        .call(obj)
        .match(/\[object (\w+)\]/)[1]
        .toLowerCase()
}

参考

www.cnblogs.com/mofish/p/33…

www.cnblogs.com/liujiekun/p…

www.cnblogs.com/zhangruiqi/…

《重学前端》模块一:JavaScript-- JavaScript类型:关于类型,有哪些你不知道的细节?