js

判断变量类型

Posted by VickyWu on April 20, 2017

利用typeof

语法 类型
typeof(‘111’) string
typeof(111) number
typeof([111]) object
typeof({1:1}) object
typeof(function(){}) function
typeof(/w/) object
typeof(null) object

利用instance of 和 利用原型链

A instance of B

A在B的原型链上

同利用原型链

function _instanceof(A, B) {
    var O = B.prototype;// 取B的显示原型
    A = A.__proto__;// 取A的隐式原型
    while (true) {
        //Object.prototype.__proto__ === null
        if (A === null)
            return false;
        if (O === A)// 这里重点:当 O 严格等于 A 时,返回 true
            return true;
        A = A.__proto__;
    }
}

通用方法

isArray:function (a) {
    return Object.prototype.toString.call(a) === '[object Array]';
},
isString:function (a) {
    return Object.prototype.toString.call(a) === '[object String]';
},
isNumber:function (a) {
    return Object.prototype.toString.call(a) === '[object Number]';
},
isFunction:function (a) {
    return Object.prototype.toString.call(a) === '[object Function]';
},
isNull:function (a) {
    return Object.prototype.toString.call(a) === '[object Null]';
},
isRegExp:function (a) {
    return Object.prototype.toString.call(a) === '[object RegExp]';
},
has:function (a,b) {          
    if(Object.prototype.toString.call(a)==='[object Array]'){
        for(var i in a){
            if(i==b){
                return true;
            }
        }
        return false;
    }

    if(Object.prototype.toString.call(a)==='[object Object]'){
        return b in a;
    }
},